@@ -142,7 +142,7 @@ proc encrypt(
142
142
143
143
inc state.n
144
144
if state.n > NonceMax :
145
- raise newException ( NoiseNonceMaxError , " Noise max nonce value reached" )
145
+ raise ( ref NoiseNonceMaxError )(msg: " Noise max nonce value reached" )
146
146
147
147
proc encryptWithAd (state: var CipherState , ad, data: openArray [byte ]): seq [byte ]
148
148
{.raises : [NoiseNonceMaxError ].} =
@@ -168,10 +168,11 @@ proc decryptWithAd(state: var CipherState, ad, data: openArray[byte]): seq[byte]
168
168
trace " decryptWithAd" , tagIn = tagIn.shortLog, tagOut = tagOut.shortLog, nonce = state.n
169
169
if tagIn != tagOut:
170
170
debug " decryptWithAd failed" , data = shortLog (data)
171
- raise newException (NoiseDecryptTagError , " decryptWithAd failed tag authentication." )
171
+ raise (ref NoiseDecryptTagError )(msg:
172
+ " decryptWithAd failed tag authentication." )
172
173
inc state.n
173
174
if state.n > NonceMax :
174
- raise newException ( NoiseNonceMaxError , " Noise max nonce value reached" )
175
+ raise ( ref NoiseNonceMaxError )(msg: " Noise max nonce value reached" )
175
176
176
177
# Symmetricstate
177
178
@@ -181,8 +182,7 @@ proc init(_: type[SymmetricState]): SymmetricState =
181
182
result .cs = CipherState (k: EmptyKey )
182
183
183
184
proc mixKey (ss: var SymmetricState , ikm: ChaChaPolyKey ) =
184
- var
185
- temp_keys: array [2 , ChaChaPolyKey ]
185
+ var temp_keys: array [2 , ChaChaPolyKey ]
186
186
sha256.hkdf (ss.ck, ikm, [], temp_keys)
187
187
ss.ck = temp_keys[0 ]
188
188
ss.cs = CipherState (k: temp_keys[1 ])
@@ -198,8 +198,7 @@ proc mixHash(ss: var SymmetricState, data: openArray[byte]) =
198
198
199
199
# We might use this for other handshake patterns/tokens
200
200
proc mixKeyAndHash (ss: var SymmetricState , ikm: openArray [byte ]) {.used .} =
201
- var
202
- temp_keys: array [3 , ChaChaPolyKey ]
201
+ var temp_keys: array [3 , ChaChaPolyKey ]
203
202
sha256.hkdf (ss.ck, ikm, [], temp_keys)
204
203
ss.ck = temp_keys[0 ]
205
204
ss.mixHash (temp_keys[1 ])
@@ -234,7 +233,8 @@ proc init(_: type[HandshakeState]): HandshakeState =
234
233
235
234
template write_e : untyped =
236
235
trace " noise write e"
237
- # Sets e (which must be empty) to GENERATE_KEYPAIR(). Appends e.public_key to the buffer. Calls MixHash(e.public_key).
236
+ # Sets e (which must be empty) to GENERATE_KEYPAIR().
237
+ # Appends e.public_key to the buffer. Calls MixHash(e.public_key).
238
238
hs.e = genKeyPair (p.rng[])
239
239
msg.add hs.e.publicKey
240
240
hs.ss.mixHash (hs.e.publicKey)
@@ -275,26 +275,28 @@ template read_e: untyped =
275
275
trace " noise read e" , size = msg.len
276
276
277
277
if msg.len < Curve25519Key .len:
278
- raise newException ( NoiseHandshakeError , " Noise E, expected more data" )
278
+ raise ( ref NoiseHandshakeError )(msg: " Noise E, expected more data" )
279
279
280
- # Sets re (which must be empty) to the next DHLEN bytes from the message. Calls MixHash(re.public_key).
280
+ # Sets re (which must be empty) to the next DHLEN bytes from the message.
281
+ # Calls MixHash(re.public_key).
281
282
hs.re[0 .. Curve25519Key .high] = msg.toOpenArray (0 , Curve25519Key .high)
282
283
msg.consume (Curve25519Key .len)
283
284
hs.ss.mixHash (hs.re)
284
285
285
286
template read_s : untyped =
286
287
trace " noise read s" , size = msg.len
287
- # Sets temp to the next DHLEN + 16 bytes of the message if HasKey() == True, or to the next DHLEN bytes otherwise.
288
+ # Sets temp to the next DHLEN + 16 bytes of the message if HasKey() == True,
289
+ # or to the next DHLEN bytes otherwise.
288
290
# Sets rs (which must be empty) to DecryptAndHash(temp).
289
291
let
290
292
rsLen =
291
293
if hs.ss.cs.hasKey:
292
294
if msg.len < Curve25519Key .len + ChaChaPolyTag .len:
293
- raise newException ( NoiseHandshakeError , " Noise S, expected more data" )
295
+ raise ( ref NoiseHandshakeError )(msg: " Noise S, expected more data" )
294
296
Curve25519Key .len + ChaChaPolyTag .len
295
297
else :
296
298
if msg.len < Curve25519Key .len:
297
- raise newException ( NoiseHandshakeError , " Noise S, expected more data" )
299
+ raise ( ref NoiseHandshakeError )(msg: " Noise S, expected more data" )
298
300
Curve25519Key .len
299
301
hs.rs[0 .. Curve25519Key .high] =
300
302
hs.ss.decryptAndHash (msg.toOpenArray (0 , rsLen - 1 ))
@@ -315,7 +317,11 @@ proc readFrame(
315
317
await sconn.readExactly (addr buffer[0 ], buffer.len)
316
318
return buffer
317
319
318
- proc writeFrame (sconn: Connection , buf: openArray [byte ]): Future [void ] =
320
+ proc writeFrame (
321
+ sconn: Connection ,
322
+ buf: openArray [byte ]
323
+ ): Future [void ] {.async : (raises: [
324
+ CancelledError , LPStreamError ], raw: true ).} =
319
325
doAssert buf.len <= uint16 .high.int
320
326
var
321
327
lesize = buf.len.uint16
@@ -326,13 +332,24 @@ proc writeFrame(sconn: Connection, buf: openArray[byte]): Future[void] =
326
332
outbuf &= buf
327
333
sconn.write (outbuf)
328
334
329
- proc receiveHSMessage (sconn: Connection ): Future [seq [byte ]] = readFrame (sconn)
330
- proc sendHSMessage (sconn: Connection , buf: openArray [byte ]): Future [void ] =
335
+ proc receiveHSMessage (
336
+ sconn: Connection
337
+ ): Future [seq [byte ]] {.async : (raises: [
338
+ CancelledError , LPStreamError ], raw: true ).} =
339
+ readFrame (sconn)
340
+
341
+ proc sendHSMessage (
342
+ sconn: Connection ,
343
+ buf: openArray [byte ]
344
+ ): Future [void ] {.async : (raises: [
345
+ CancelledError , LPStreamError ], raw: true ).} =
331
346
writeFrame (sconn, buf)
332
347
333
348
proc handshakeXXOutbound (
334
349
p: Noise , conn: Connection ,
335
- p2pSecret: seq [byte ]): Future [HandshakeResult ] {.async .} =
350
+ p2pSecret: seq [byte ]
351
+ ): Future [HandshakeResult ] {.async : (raises: [
352
+ CancelledError , LPStreamError ]).} =
336
353
const initiator = true
337
354
var
338
355
hs = HandshakeState .init ()
@@ -374,13 +391,16 @@ proc handshakeXXOutbound(
374
391
await conn.sendHSMessage (msg.data)
375
392
376
393
let (cs1, cs2) = hs.ss.split ()
377
- return HandshakeResult (cs1: cs1, cs2: cs2, remoteP2psecret: remoteP2psecret, rs: hs.rs)
394
+ return HandshakeResult (
395
+ cs1: cs1, cs2: cs2, remoteP2psecret: remoteP2psecret, rs: hs.rs)
378
396
finally :
379
397
burnMem (hs)
380
398
381
399
proc handshakeXXInbound (
382
400
p: Noise , conn: Connection ,
383
- p2pSecret: seq [byte ]): Future [HandshakeResult ] {.async .} =
401
+ p2pSecret: seq [byte ]
402
+ ): Future [HandshakeResult ] {.async : (raises: [
403
+ CancelledError , LPStreamError ]).} =
384
404
const initiator = false
385
405
386
406
var
@@ -424,7 +444,8 @@ proc handshakeXXInbound(
424
444
let
425
445
remoteP2psecret = hs.ss.decryptAndHash (msg.data)
426
446
(cs1, cs2) = hs.ss.split ()
427
- return HandshakeResult (cs1: cs1, cs2: cs2, remoteP2psecret: remoteP2psecret, rs: hs.rs)
447
+ return HandshakeResult (
448
+ cs1: cs1, cs2: cs2, remoteP2psecret: remoteP2psecret, rs: hs.rs)
428
449
finally :
429
450
burnMem (hs)
430
451
@@ -486,7 +507,8 @@ method write*(
486
507
try :
487
508
encryptFrame (
488
509
sconn,
489
- cipherFrames.toOpenArray (woffset, woffset + chunkSize + FramingSize - 1 ),
510
+ cipherFrames.toOpenArray (
511
+ woffset, woffset + chunkSize + FramingSize - 1 ),
490
512
message.toOpenArray (offset, offset + chunkSize - 1 ))
491
513
except NoiseNonceMaxError as exc:
492
514
debug " Noise nonce exceeded"
@@ -509,21 +531,28 @@ method write*(
509
531
# sequencing issues
510
532
sconn.stream.write (cipherFrames)
511
533
512
- method handshake * (p: Noise , conn: Connection , initiator: bool , peerId: Opt [PeerId ]): Future [SecureConn ] {.async .} =
534
+ method handshake * (
535
+ p: Noise ,
536
+ conn: Connection ,
537
+ initiator: bool ,
538
+ peerId: Opt [PeerId ]
539
+ ): Future [SecureConn ] {.async : (raises: [CancelledError , LPStreamError ]).} =
513
540
trace " Starting Noise handshake" , conn, initiator
514
541
515
542
let timeout = conn.timeout
516
543
conn.timeout = HandshakeTimeout
517
544
518
545
# https://github.com/libp2p/specs/tree/master/noise#libp2p-data-in-handshake-messages
519
- let
520
- signedPayload = p.localPrivateKey.sign (
521
- PayloadString & p.noiseKeys.publicKey.getBytes).tryGet ()
546
+ let signedPayload = p.localPrivateKey.sign (
547
+ PayloadString & p.noiseKeys.publicKey.getBytes)
548
+ if signedPayload.isErr ():
549
+ raise (ref NoiseHandshakeError )(msg:
550
+ " Failed to sign public key: " & $ signedPayload.error ())
522
551
523
552
var
524
553
libp2pProof = initProtoBuffer ()
525
554
libp2pProof.write (1 , p.localPublicKey)
526
- libp2pProof.write (2 , signedPayload.getBytes ())
555
+ libp2pProof.write (2 , signedPayload.get (). getBytes ())
527
556
# data field also there but not used!
528
557
libp2pProof.finish ()
529
558
@@ -542,29 +571,38 @@ method handshake*(p: Noise, conn: Connection, initiator: bool, peerId: Opt[PeerI
542
571
remoteSigBytes: seq [byte ]
543
572
544
573
if not remoteProof.getField (1 , remotePubKeyBytes).valueOr (false ):
545
- raise newException (NoiseHandshakeError , " Failed to deserialize remote public key bytes. (initiator: " & $ initiator & " )" )
574
+ raise (ref NoiseHandshakeError )(msg:
575
+ " Failed to deserialize remote public key bytes. (initiator: " &
576
+ $ initiator & " )" )
546
577
if not remoteProof.getField (2 , remoteSigBytes).valueOr (false ):
547
- raise newException (NoiseHandshakeError , " Failed to deserialize remote signature bytes. (initiator: " & $ initiator & " )" )
578
+ raise (ref NoiseHandshakeError )(msg:
579
+ " Failed to deserialize remote signature bytes. (initiator: " &
580
+ $ initiator & " )" )
548
581
549
582
if not remotePubKey.init (remotePubKeyBytes):
550
- raise newException (NoiseHandshakeError , " Failed to decode remote public key. (initiator: " & $ initiator & " )" )
583
+ raise (ref NoiseHandshakeError )(msg:
584
+ " Failed to decode remote public key. (initiator: " & $ initiator & " )" )
551
585
if not remoteSig.init (remoteSigBytes):
552
- raise newException (NoiseHandshakeError , " Failed to decode remote signature. (initiator: " & $ initiator & " )" )
586
+ raise (ref NoiseHandshakeError )(msg:
587
+ " Failed to decode remote signature. (initiator: " & $ initiator & " )" )
553
588
554
589
let verifyPayload = PayloadString & handshakeRes.rs.getBytes
555
590
if not remoteSig.verify (verifyPayload, remotePubKey):
556
- raise newException (NoiseHandshakeError , " Noise handshake signature verify failed." )
591
+ raise (ref NoiseHandshakeError )(msg:
592
+ " Noise handshake signature verify failed." )
557
593
else :
558
594
trace " Remote signature verified" , conn
559
595
560
596
let pid = PeerId .init (remotePubKey).valueOr:
561
- raise newException (NoiseHandshakeError , " Invalid remote peer id: " & $ error)
597
+ raise (ref NoiseHandshakeError )(msg:
598
+ " Invalid remote peer id: " & $ error)
562
599
563
600
trace " Remote peer id" , pid = $ pid
564
601
565
602
peerId.withValue (targetPid):
566
603
if not targetPid.validate ():
567
- raise newException (NoiseHandshakeError , " Failed to validate expected peerId." )
604
+ raise (ref NoiseHandshakeError )(msg:
605
+ " Failed to validate expected peerId." )
568
606
569
607
if pid != targetPid:
570
608
var
@@ -574,7 +612,8 @@ method handshake*(p: Noise, conn: Connection, initiator: bool, peerId: Opt[PeerI
574
612
initiator, dealt_peer = conn,
575
613
dealt_key = $ failedKey, received_peer = $ pid,
576
614
received_key = $ remotePubKey
577
- raise newException (NoiseHandshakeError , " Noise handshake, peer id don't match! " & $ pid & " != " & $ targetPid)
615
+ raise (ref NoiseHandshakeError )(msg:
616
+ " Noise handshake, peer id don't match! " & $ pid & " != " & $ targetPid)
578
617
conn.peerId = pid
579
618
580
619
var tmp = NoiseConnection .new (conn, conn.peerId, conn.observedAddr)
0 commit comments