small cleanup

This commit is contained in:
Dmitriy Ryajov 2020-04-04 20:43:05 -06:00
parent 8dda6c289d
commit bae4713a85
1 changed files with 16 additions and 15 deletions

View File

@ -16,6 +16,7 @@ import ../../peer
import ../../peerinfo import ../../peerinfo
import ../../protobuf/minprotobuf import ../../protobuf/minprotobuf
import ../../utility import ../../utility
import ../../stream/lpstream
import secure, import secure,
../../crypto/[crypto, chacha20poly1305, curve25519, hkdf], ../../crypto/[crypto, chacha20poly1305, curve25519, hkdf],
../../stream/bufferstream ../../stream/bufferstream
@ -26,7 +27,7 @@ logScope:
const const
# https://godoc.org/github.com/libp2p/go-libp2p-noise#pkg-constants # https://godoc.org/github.com/libp2p/go-libp2p-noise#pkg-constants
NoiseCodec* = "/noise" NoiseCodec* = "/noise"
PayloadString = "noise-libp2p-static-key:" PayloadString = "noise-libp2p-static-key:"
ProtocolXXName = "Noise_XX_25519_ChaChaPoly_SHA256" ProtocolXXName = "Noise_XX_25519_ChaChaPoly_SHA256"
@ -41,7 +42,7 @@ type
KeyPair = object KeyPair = object
privateKey: Curve25519Key privateKey: Curve25519Key
publicKey: Curve25519Key publicKey: Curve25519Key
# https://noiseprotocol.org/noise.html#the-cipherstate-object # https://noiseprotocol.org/noise.html#the-cipherstate-object
CipherState = object CipherState = object
k: ChaChaPolyKey k: ChaChaPolyKey
@ -66,7 +67,7 @@ type
cs2: CipherState cs2: CipherState
remoteP2psecret: seq[byte] remoteP2psecret: seq[byte]
rs: Curve25519Key rs: Curve25519Key
Noise* = ref object of Secure Noise* = ref object of Secure
localPrivateKey: PrivateKey localPrivateKey: PrivateKey
localPublicKey: PublicKey localPublicKey: PublicKey
@ -89,7 +90,7 @@ type
proc genKeyPair(): KeyPair = proc genKeyPair(): KeyPair =
result.privateKey = Curve25519Key.random() result.privateKey = Curve25519Key.random()
result.publicKey = result.privateKey.public() result.publicKey = result.privateKey.public()
proc hashProtocol(name: string): MDigest[256] = proc hashProtocol(name: string): MDigest[256] =
# If protocol_name is less than or equal to HASHLEN bytes in length, # If protocol_name is less than or equal to HASHLEN bytes in length,
# sets h equal to protocol_name with zero bytes appended to make HASHLEN bytes. # sets h equal to protocol_name with zero bytes appended to make HASHLEN bytes.
@ -195,7 +196,7 @@ proc split(ss: var SymmetricState): tuple[cs1, cs2: CipherState] =
proc init(_: type[HandshakeState]): HandshakeState = proc init(_: type[HandshakeState]): HandshakeState =
result.ss = SymmetricState.init() result.ss = SymmetricState.init()
template write_e: untyped = template write_e: untyped =
trace "noise write e" trace "noise write e"
# Sets e (which must be empty) to GENERATE_KEYPAIR(). Appends e.public_key to the buffer. Calls MixHash(e.public_key). # Sets e (which must be empty) to GENERATE_KEYPAIR(). Appends e.public_key to the buffer. Calls MixHash(e.public_key).
@ -302,7 +303,7 @@ proc packNoisePayload(payload: openarray[byte]): seq[byte] =
if result.len > uint16.high.int: if result.len > uint16.high.int:
raise newException(NoiseOversizedPayloadError, "Trying to send an unsupported oversized payload over Noise") raise newException(NoiseOversizedPayloadError, "Trying to send an unsupported oversized payload over Noise")
trace "packed noise payload", inSize = payload.len, outSize = result.len trace "packed noise payload", inSize = payload.len, outSize = result.len
proc unpackNoisePayload(payload: var seq[byte]) = proc unpackNoisePayload(payload: var seq[byte]) =
@ -312,7 +313,7 @@ proc unpackNoisePayload(payload: var seq[byte]) =
if size > (payload.len - 2): if size > (payload.len - 2):
raise newException(NoiseOversizedPayloadError, "Received a wrong payload size") raise newException(NoiseOversizedPayloadError, "Received a wrong payload size")
payload = payload[2..^((payload.len - size) - 1)] payload = payload[2..^((payload.len - size) - 1)]
trace "unpacked noise payload", size = payload.len trace "unpacked noise payload", size = payload.len
@ -362,7 +363,7 @@ proc handshakeXXOutbound(p: Noise, conn: Connection, p2pProof: ProtoBuffer): Fut
msg &= hs.ss.encryptAndHash(packed) msg &= hs.ss.encryptAndHash(packed)
await conn.sendHSMessage(msg) await conn.sendHSMessage(msg)
let (cs1, cs2) = hs.ss.split() let (cs1, cs2) = hs.ss.split()
return HandshakeResult(cs1: cs1, cs2: cs2, remoteP2psecret: remoteP2psecret, rs: hs.rs) return HandshakeResult(cs1: cs1, cs2: cs2, remoteP2psecret: remoteP2psecret, rs: hs.rs)
@ -426,9 +427,9 @@ method readMessage(sconn: NoiseConnection): Future[seq[byte]] {.async.} =
var plain = sconn.readCs.decryptWithAd([], cipher) var plain = sconn.readCs.decryptWithAd([], cipher)
unpackNoisePayload(plain) unpackNoisePayload(plain)
return plain return plain
except AsyncStreamIncompleteError: except LPStreamIncompleteError:
trace "Connection dropped while reading" trace "Connection dropped while reading"
except AsyncStreamReadError: except LPStreamReadError:
trace "Error reading from connection" trace "Error reading from connection"
method writeMessage(sconn: NoiseConnection, message: seq[byte]): Future[void] {.async.} = method writeMessage(sconn: NoiseConnection, message: seq[byte]): Future[void] {.async.} =
@ -460,7 +461,7 @@ method handshake*(p: Noise, conn: Connection, initiator: bool = false): Future[S
# https://github.com/libp2p/specs/tree/master/noise#libp2p-data-in-handshake-messages # https://github.com/libp2p/specs/tree/master/noise#libp2p-data-in-handshake-messages
let let
signedPayload = p.localPrivateKey.sign(PayloadString.toBytes & p.noisePublicKey.getBytes) signedPayload = p.localPrivateKey.sign(PayloadString.toBytes & p.noisePublicKey.getBytes)
var var
libp2pProof = initProtoBuffer() libp2pProof = initProtoBuffer()
@ -489,7 +490,7 @@ method handshake*(p: Noise, conn: Connection, initiator: bool = false): Future[S
raise newException(NoiseHandshakeError, "Noise handshake signature verify failed.") raise newException(NoiseHandshakeError, "Noise handshake signature verify failed.")
else: else:
trace "Remote signature verified" trace "Remote signature verified"
if initiator and not isNil(conn.peerInfo): if initiator and not isNil(conn.peerInfo):
let pid = PeerID.init(remotePubKey) let pid = PeerID.init(remotePubKey)
if not conn.peerInfo.peerId.validate(): if not conn.peerInfo.peerId.validate():
@ -508,10 +509,10 @@ method handshake*(p: Noise, conn: Connection, initiator: bool = false): Future[S
secure.readCs = handshakeRes.cs1 secure.readCs = handshakeRes.cs1
secure.writeCs = handshakeRes.cs2 secure.writeCs = handshakeRes.cs2
debug "Noise handshake completed!" trace "Noise handshake completed!"
return secure return secure
method init*(p: Noise) {.gcsafe.} = method init*(p: Noise) {.gcsafe.} =
procCall Secure(p).init() procCall Secure(p).init()
p.codec = NoiseCodec p.codec = NoiseCodec
@ -523,7 +524,7 @@ method secure*(p: Noise, conn: Connection): Future[Connection] {.async, gcsafe.}
warn "securing connection failed", msg = exc.msg warn "securing connection failed", msg = exc.msg
if not conn.closed(): if not conn.closed():
await conn.close() await conn.close()
proc newNoise*(privateKey: PrivateKey; outgoing: bool = true; commonPrologue: seq[byte] = @[]): Noise = proc newNoise*(privateKey: PrivateKey; outgoing: bool = true; commonPrologue: seq[byte] = @[]): Noise =
new result new result
result.outgoing = outgoing result.outgoing = outgoing