2019-12-06 02:16:18 +00:00
|
|
|
## Nim-LibP2P
|
|
|
|
## Copyright (c) 2019 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
|
|
|
import options
|
|
|
|
import chronicles
|
|
|
|
import nimcrypto/sysrand
|
|
|
|
import messages, protobuf,
|
|
|
|
../../../peer,
|
2019-12-07 16:36:39 +00:00
|
|
|
../../../peerinfo,
|
2019-12-06 02:16:18 +00:00
|
|
|
../../../crypto/crypto,
|
|
|
|
../../../protobuf/minprotobuf
|
|
|
|
|
|
|
|
logScope:
|
|
|
|
topic = "PubSubMessage"
|
|
|
|
|
2019-12-07 16:36:39 +00:00
|
|
|
const PubSubPrefix = "libp2p-pubsub:"
|
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
proc msgId*(m: Message): string =
|
|
|
|
m.seqno.toHex() & PeerID.init(m.fromPeer).pretty
|
|
|
|
|
|
|
|
proc fromPeerId*(m: Message): PeerId =
|
|
|
|
PeerID.init(m.fromPeer)
|
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc sign*(p: PeerInfo, msg: Message): Message {.gcsafe.} =
|
2019-12-06 02:16:18 +00:00
|
|
|
var buff = initProtoBuffer()
|
|
|
|
encodeMessage(msg, buff)
|
2019-12-07 16:36:39 +00:00
|
|
|
let prefix = cast[seq[byte]](PubSubPrefix)
|
2019-12-06 02:16:18 +00:00
|
|
|
if buff.buffer.len > 0:
|
|
|
|
result = msg
|
2019-12-07 16:36:39 +00:00
|
|
|
result.signature = p.privateKey.
|
|
|
|
sign(prefix & buff.buffer).
|
|
|
|
getBytes()
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2019-12-07 16:36:39 +00:00
|
|
|
proc verify*(p: PeerInfo, m: Message): bool =
|
2019-12-06 02:16:18 +00:00
|
|
|
if m.signature.len > 0 and m.key.len > 0:
|
|
|
|
var msg = m
|
|
|
|
msg.signature = @[]
|
|
|
|
msg.key = @[]
|
|
|
|
|
|
|
|
var buff = initProtoBuffer()
|
|
|
|
encodeMessage(msg, buff)
|
|
|
|
|
|
|
|
var remote: Signature
|
|
|
|
var key: PublicKey
|
|
|
|
if remote.init(m.signature) and key.init(m.key):
|
|
|
|
result = remote.verify(buff.buffer, key)
|
|
|
|
|
2019-12-07 16:36:39 +00:00
|
|
|
proc newMessage*(p: PeerInfo,
|
2019-12-06 02:16:18 +00:00
|
|
|
data: seq[byte],
|
|
|
|
name: string,
|
2019-12-08 21:06:58 +00:00
|
|
|
sign: bool = true): Message {.gcsafe.} =
|
2019-12-06 02:16:18 +00:00
|
|
|
var seqno: seq[byte] = newSeq[byte](20)
|
2019-12-07 16:36:39 +00:00
|
|
|
if p.publicKey.isSome and randomBytes(addr seqno[0], 20) > 0:
|
|
|
|
var key: seq[byte] = p.publicKey.get().getBytes()
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2019-12-07 16:36:39 +00:00
|
|
|
result = Message(fromPeer: p.peerId.getBytes(),
|
2019-12-06 02:16:18 +00:00
|
|
|
data: data,
|
|
|
|
seqno: seqno,
|
|
|
|
topicIDs: @[name])
|
|
|
|
if sign:
|
2019-12-07 16:36:39 +00:00
|
|
|
result = p.sign(result)
|
2019-12-06 02:16:18 +00:00
|
|
|
|
|
|
|
result.key = key
|