nim-libp2p/libp2p/peerid.nim

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

222 lines
6.4 KiB
Nim
Raw Normal View History

2022-07-01 18:19:57 +00:00
# Nim-LibP2P
2023-01-20 14:47:40 +00:00
# Copyright (c) 2023 Status Research & Development GmbH
2022-07-01 18:19:57 +00:00
# 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.
## This module implementes API for libp2p peer.
2023-06-07 11:12:49 +00:00
{.push raises: [].}
2022-07-01 18:19:57 +00:00
{.push public.}
import
std/[hashes, strutils],
stew/[base58, results],
chronicles,
nimcrypto/utils,
2022-07-01 18:19:57 +00:00
utility,
./crypto/crypto,
./multicodec,
./multihash,
./vbuffer,
./protobuf/minprotobuf
2022-07-01 18:19:57 +00:00
export results, utility
const maxInlineKeyLength* = 42
2021-12-16 10:05:20 +00:00
type PeerId* = object
data*: seq[byte]
2021-12-16 10:05:20 +00:00
func `$`*(pid: PeerId): string =
## Return base58 encoded ``pid`` representation.
2021-11-04 10:19:17 +00:00
# This unusual call syntax is used to avoid a strange Nim compilation error
base58.encode(Base58, pid.data)
func shortLog*(pid: PeerId): string =
## Returns compact string representation of ``pid``.
var spid = $pid
if len(spid) > 10:
spid[3] = '*'
2023-06-07 11:12:49 +00:00
spid.delete(4 .. spid.high - 6)
spid
2021-12-16 10:05:20 +00:00
chronicles.formatIt(PeerId):
shortLog(it)
2021-12-16 10:05:20 +00:00
func toBytes*(pid: PeerId, data: var openArray[byte]): int =
## Store PeerId ``pid`` to array of bytes ``data``.
##
## Returns number of bytes needed to store ``pid``.
result = len(pid.data)
if len(data) >= result and result > 0:
copyMem(addr data[0], unsafeAddr pid.data[0], result)
2021-12-16 10:05:20 +00:00
template getBytes*(pid: PeerId): seq[byte] =
## Return PeerId ``pid`` as array of bytes.
pid.data
2021-12-16 10:05:20 +00:00
func hex*(pid: PeerId): string =
## Returns hexadecimal string representation of ``pid``.
toHex(pid.data)
2021-12-16 10:05:20 +00:00
template len*(pid: PeerId): int =
## Returns length of ``pid`` binary representation.
len(pid.data)
2021-12-16 10:05:20 +00:00
func cmp*(a, b: PeerId): int =
## Compares two peer ids ``a`` and ``b``.
## Returns:
##
## | 0 iff a == b
## | < 0 iff a < b
## | > 0 iff a > b
var i = 0
var m = min(len(a.data), len(b.data))
while i < m:
result = ord(a.data[i]) - ord(b.data[i])
if result != 0:
return
inc(i)
result = len(a.data) - len(b.data)
2021-12-16 10:05:20 +00:00
template `<=`*(a, b: PeerId): bool =
(cmp(a, b) <= 0)
2021-12-16 10:05:20 +00:00
template `<`*(a, b: PeerId): bool =
(cmp(a, b) < 0)
2021-12-16 10:05:20 +00:00
template `>=`*(a, b: PeerId): bool =
(cmp(a, b) >= 0)
2021-12-16 10:05:20 +00:00
template `>`*(a, b: PeerId): bool =
(cmp(a, b) > 0)
2021-12-16 10:05:20 +00:00
template `==`*(a, b: PeerId): bool =
(cmp(a, b) == 0)
2021-12-16 10:05:20 +00:00
template hash*(pid: PeerId): Hash =
hash(pid.data)
2021-12-16 10:05:20 +00:00
func validate*(pid: PeerId): bool =
## Validate check if ``pid`` is empty or not.
len(pid.data) > 0 and MultiHash.validate(pid.data)
2021-12-16 10:05:20 +00:00
func hasPublicKey*(pid: PeerId): bool =
## Returns ``true`` if ``pid`` is small enough to hold public key inside.
if len(pid.data) > 0:
var mh: MultiHash
if MultiHash.decode(pid.data, mh).isOk:
if mh.mcodec == multiCodec("identity"):
result = true
2021-12-16 10:05:20 +00:00
func extractPublicKey*(pid: PeerId, pubkey: var PublicKey): bool =
## Returns ``true`` if public key was successfully decoded from PeerId
## ``pid``and stored to ``pubkey``.
##
## Returns ``false`` otherwise.
if len(pid.data) > 0:
var mh: MultiHash
if MultiHash.decode(pid.data, mh).isOk:
if mh.mcodec == multiCodec("identity"):
let length = len(mh.data.buffer)
result = pubkey.init(mh.data.buffer.toOpenArray(mh.dpos, length - 1))
2021-12-16 10:05:20 +00:00
func init*(pid: var PeerId, data: openArray[byte]): bool =
## Initialize peer id from raw binary representation ``data``.
##
## Returns ``true`` if peer was successfully initialiazed.
2021-12-16 10:05:20 +00:00
var p = PeerId(data: @data)
if p.validate():
pid = p
result = true
2021-12-16 10:05:20 +00:00
func init*(pid: var PeerId, data: string): bool =
## Initialize peer id from base58 encoded string representation.
##
## Returns ``true`` if peer was successfully initialiazed.
var p = newSeq[byte](len(data) + 4)
var length = 0
if Base58.decode(data, p, length) == Base58Status.Success:
p.setLen(length)
2021-12-16 10:05:20 +00:00
var opid: PeerId
2022-10-20 12:52:02 +00:00
opid.data = p
if opid.validate():
pid = opid
result = true
2021-12-16 10:05:20 +00:00
func init*(t: typedesc[PeerId], data: openArray[byte]): Result[PeerId, cstring] =
## Create new peer id from raw binary representation ``data``.
2021-12-16 10:05:20 +00:00
var res: PeerId
if not init(res, data):
2021-12-16 10:05:20 +00:00
err("peerid: incorrect PeerId binary form")
else:
ok(res)
2021-12-16 10:05:20 +00:00
func init*(t: typedesc[PeerId], data: string): Result[PeerId, cstring] =
## Create new peer id from base58 encoded string representation ``data``.
2021-12-16 10:05:20 +00:00
var res: PeerId
if not init(res, data):
2021-12-16 10:05:20 +00:00
err("peerid: incorrect PeerId string")
else:
ok(res)
2021-12-16 10:05:20 +00:00
func init*(t: typedesc[PeerId], pubkey: PublicKey): Result[PeerId, cstring] =
## Create new peer id from public key ``pubkey``.
var pubraw =
?pubkey.getBytes().orError(cstring("peerid: failed to get bytes from given key"))
var mh: MultiHash
if len(pubraw) <= maxInlineKeyLength:
mh = ?MultiHash.digest("identity", pubraw)
else:
mh = ?MultiHash.digest("sha2-256", pubraw)
2021-12-16 10:05:20 +00:00
ok(PeerId(data: mh.data.buffer))
2021-12-16 10:05:20 +00:00
func init*(t: typedesc[PeerId], seckey: PrivateKey): Result[PeerId, cstring] =
## Create new peer id from private key ``seckey``.
2021-12-16 10:05:20 +00:00
PeerId.init(?seckey.getPublicKey().orError(cstring("invalid private key")))
proc random*(t: typedesc[PeerId], rng = newRng()): Result[PeerId, cstring] =
## Create new peer id with random public key.
let randomKey = PrivateKey.random(Secp256k1, rng[])[]
PeerId.init(randomKey).orError(cstring("failed to generate random key"))
2021-12-16 10:05:20 +00:00
func match*(pid: PeerId, pubkey: PublicKey): bool =
## Returns ``true`` if ``pid`` matches public key ``pubkey``.
PeerId.init(pubkey) == Result[PeerId, cstring].ok(pid)
2021-12-16 10:05:20 +00:00
func match*(pid: PeerId, seckey: PrivateKey): bool =
## Returns ``true`` if ``pid`` matches private key ``seckey``.
PeerId.init(seckey) == Result[PeerId, cstring].ok(pid)
## Serialization/Deserialization helpers
2021-12-16 10:05:20 +00:00
func write*(vb: var VBuffer, pid: PeerId) =
## Write PeerId value ``peerid`` to buffer ``vb``.
vb.writeSeq(pid.data)
2021-12-16 10:05:20 +00:00
func write*(pb: var ProtoBuffer, field: int, pid: PeerId) =
## Write PeerId value ``peerid`` to object ``pb`` using ProtoBuf's encoding.
write(pb, field, pid.data)
func getField*(
pb: ProtoBuffer, field: int, pid: var PeerId
2021-12-16 10:05:20 +00:00
): ProtoResult[bool] {.inline.} =
## Read ``PeerId`` from ProtoBuf's message and validate it
var buffer: seq[byte]
let res = ?pb.getField(field, buffer)
if not (res):
ok(false)
else:
2021-12-16 10:05:20 +00:00
var peerId: PeerId
if peerId.init(buffer):
pid = peerId
ok(true)
else:
err(ProtoError.IncorrectBlob)