Skip to content

Commit 3e5d450

Browse files
vasco-santosjacobheun
authored andcommitted
feat: signed peer records record manager
1 parent 098f3d1 commit 3e5d450

File tree

12 files changed

+715
-1
lines changed

12 files changed

+715
-1
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
"merge-options": "^2.0.0",
6666
"moving-average": "^1.0.0",
6767
"multiaddr": "^7.4.3",
68+
"multicodec": "^1.0.2",
6869
"multistream-select": "^0.15.0",
6970
"mutable-proxy": "^1.0.0",
7071
"node-forge": "^0.9.1",

src/index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,13 @@ const { codes, messages } = require('./errors')
1818

1919
const AddressManager = require('./address-manager')
2020
const ConnectionManager = require('./connection-manager')
21+
const RecordManager = require('./record-manager')
22+
const TransportManager = require('./transport-manager')
23+
2124
const Circuit = require('./circuit')
2225
const Dialer = require('./dialer')
2326
const Keychain = require('./keychain')
2427
const Metrics = require('./metrics')
25-
const TransportManager = require('./transport-manager')
2628
const Upgrader = require('./upgrader')
2729
const PeerStore = require('./peer-store')
2830
const PersistentPeerStore = require('./peer-store/persistent')
@@ -60,6 +62,9 @@ class Libp2p extends EventEmitter {
6062
this.addresses = this._options.addresses
6163
this.addressManager = new AddressManager(this._options.addresses)
6264

65+
// Records
66+
this.RecordManager = new RecordManager(this)
67+
6368
this._modules = this._options.modules
6469
this._config = this._options.config
6570
this._transport = [] // Transport instances/references

src/record-manager/README.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Record Manager
2+
3+
All libp2p nodes keep a `PeerStore`, that among other information stores a set of known addresses for each peer. Addresses for a peer can come from a variety of sources.
4+
5+
Libp2p peer records were created to enable the distributiion of verifiable address records, which we can prove originated from the addressed peer itself.
6+
7+
With such guarantees, libp2p can prioritize addresses based on their authenticity, with the most strict strategy being to only dial certified addresses.
8+
9+
The libp2p record manager is responsible for keeping a local peer record updated, as well as to inform third parties of possible updates. (TODO: REMOVE and modules: Moreover, it provides an API for the creation and validation of libp2p **envelopes**.)
10+
11+
## Envelop
12+
13+
Libp2p nodes need to store data in a public location (e.g. a DHT), or rely on potentially untrustworthy intermediaries to relay information over its lifetime. Accordingly, libp2p nodes need to be able to verify that the data came from a specific peer and that it hasn't been tampered with.
14+
15+
Libp2p provides an all-purpose data container called **envelope**, which includes a signature of the data, so that its authenticity can be verified. This envelope stores a marshaled record implementing the [interface-record](https://github.com/libp2p/js-libp2p-interfaces/tree/master/src/record).
16+
17+
Envelope signatures can be used for a variety of purposes, and a signature made for a specific purpose IS NOT be considered valid for a different purpose. We separate signatures into `domains` by prefixing the data to be signed with a string unique to each domain. This string is not contained within the envelope data. Instead, each libp2p subsystem that makes use of signed envelopes will provide their own domain string when creating the envelope, and again when validating the envelope. If the domain string used to validate it is different from the one used to sign, the signature validation will fail.
18+
19+
## Records
20+
21+
The Records are designed to be serialized to bytes and placed inside of the envelopes before being shared with other peers.
22+
23+
### Peer Record
24+
25+
A peer record contains the peers' publicly reachable listen addresses, and may be extended in the future to contain additional metadata relevant to routing.
26+
27+
Each peer record contains a `seq` field, so that we can order peer records by time and identify if a received record is more recent than the stored one.
28+
29+
They should be used either through a direct exchange (as in th libp2p identify protocol), or through a peer routing provider, such as a DHT.
30+
31+
## Libp2p flows
32+
33+
Once a libp2p node has started and is listening on a set of multiaddrs, the **Record Manager** will kick in, create a peer record for the peer and wrap it inside a signed envelope. Everytime a libp2p subsystem needs to share its peer record, it will get the cached computed peer record and send its envelope.
34+
35+
**_NOT_YET_IMPLEMENTED_** While creating peer records is fairly trivial, addresses should not be static and can be modified at arbitrary times. When a libp2p node changes its listen addresses, the **Record Manager** will compute a new peer record, wrap it inside a signed envelope and inform the interested subsystems.
36+
37+
Considering that a node can discover other peers' addresses from a variety of sources, Libp2p Peerstore should be able to differentiate the addresses that were obtained through a signed peer record. Once all these pieces are in place, we will also need a way to prioritize addresses based on their authenticity, that is, the dialer can prioritize self-certified addresses over addresses from an unknown origin.
38+
39+
When a libp2p node receives a new signed peer record, the `seq` number of the record must be compared with potentially stored records, so that we do not override correct data,
40+
41+
### Notes:
42+
43+
- Possible design for AddressBook
44+
45+
```
46+
addr_book_record
47+
\_ peer_id: bytes
48+
\_ signed_addrs: []AddrEntry
49+
\_ unsigned_addrs: []AddrEntry
50+
\_ certified_record
51+
\_ seq: bytes
52+
\_ raw: bytes
53+
```
54+
55+
## Future Work
56+
57+
- Peers may not know their own addresses. It's often impossible to automatically infer one's own public address, and peers may need to rely on third party peers to inform them of their observed public addresses.
58+
- A peer may inadvertently or maliciously sign an address that they do not control. In other words, a signature isn't a guarantee that a given address is valid.
59+
- Some addresses may be ambiguous. For example, addresses on a private subnet are valid within that subnet but are useless on the public internet.
60+
- Modular dialer? (taken from go PR notes)
61+
- With the modular dialer, users should easily be able to configure precedence. With dialer v1, anything we do to prioritise dials is gonna be spaghetti and adhoc. With the modular dialer, you’d be able to specify the order of dials when instantiating the pipeline.
62+
- Multiple parallel dials. We already have the issue where new addresses aren't added to existing dials.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'use strict'
2+
3+
const protons = require('protons')
4+
5+
const message = `
6+
message Envelope {
7+
// public_key is the public key of the keypair the enclosed payload was
8+
// signed with.
9+
bytes public_key = 1;
10+
11+
// payload_type encodes the type of payload, so that it can be deserialized
12+
// deterministically.
13+
bytes payload_type = 2;
14+
15+
// payload is the actual payload carried inside this envelope.
16+
bytes payload = 3;
17+
18+
// signature is the signature produced by the private key corresponding to
19+
// the enclosed public key, over the payload, prefixing a domain string for
20+
// additional security.
21+
bytes signature = 5;
22+
}
23+
`
24+
25+
module.exports = protons(message).Envelope

src/record-manager/envelope/index.js

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
'use strict'
2+
3+
const debug = require('debug')
4+
const log = debug('libp2p:envelope')
5+
log.error = debug('libp2p:envelope:error')
6+
const errCode = require('err-code')
7+
8+
const crypto = require('libp2p-crypto')
9+
const multicodec = require('multicodec')
10+
const PeerId = require('peer-id')
11+
12+
const Protobuf = require('./envelope.proto')
13+
14+
/**
15+
* The Envelope is responsible for keeping arbitrary signed by a libp2p peer.
16+
*/
17+
class Envelope {
18+
/**
19+
* @constructor
20+
* @param {object} params
21+
* @param {PeerId} params.peerId
22+
* @param {Buffer} params.payloadType
23+
* @param {Buffer} params.payload marshaled record
24+
* @param {Buffer} params.signature signature of the domain string :: type hint :: payload.
25+
*/
26+
constructor ({ peerId, payloadType, payload, signature }) {
27+
this.peerId = peerId
28+
this.payloadType = payloadType
29+
this.payload = payload
30+
this.signature = signature
31+
32+
// Cache
33+
this._marshal = undefined
34+
}
35+
36+
/**
37+
* Marshal the envelope content.
38+
* @return {Buffer}
39+
*/
40+
marshal () {
41+
if (this._marshal) {
42+
return this._marshal
43+
}
44+
// TODO: type for marshal (default: RSA)
45+
const publicKey = crypto.keys.marshalPublicKey(this.peerId.pubKey)
46+
47+
this._marshal = Protobuf.encode({
48+
public_key: publicKey,
49+
payload_type: this.payloadType,
50+
payload: this.payload,
51+
signature: this.signature
52+
})
53+
54+
return this._marshal
55+
}
56+
57+
/**
58+
* Verifies if the other Envelope is identical to this one.
59+
* @param {Envelope} other
60+
* @return {boolean}
61+
*/
62+
isEqual (other) {
63+
return this.peerId.pubKey.bytes.equals(other.peerId.pubKey.bytes) &&
64+
this.payloadType.equals(other.payloadType) &&
65+
this.payload.equals(other.payload) &&
66+
this.signature.equals(other.signature)
67+
}
68+
69+
/**
70+
* Validate envelope data signature for the given domain.
71+
* @param {string} domain
72+
* @return {Promise}
73+
*/
74+
async validate (domain) {
75+
const signData = createSignData(domain, this.payloadType, this.payload)
76+
77+
try {
78+
await this.peerId.pubKey.verify(signData, this.signature)
79+
} catch (_) {
80+
log.error('record signature verification failed')
81+
// TODO
82+
throw errCode(new Error('record signature verification failed'), 'ERRORS.ERR_SIGNATURE_VERIFICATION')
83+
}
84+
}
85+
}
86+
87+
exports = module.exports = Envelope
88+
89+
/**
90+
* Seal marshals the given Record, places the marshaled bytes inside an Envelope
91+
* and signs with the given private key.
92+
* @async
93+
* @param {Record} record
94+
* @param {PeerId} peerId
95+
* @return {Envelope}
96+
*/
97+
exports.seal = async (record, peerId) => {
98+
const domain = record.domain
99+
const payloadType = Buffer.from(`${multicodec.print[record.codec]}${domain}`)
100+
const payload = record.marshal()
101+
102+
const signData = createSignData(domain, payloadType, payload)
103+
const signature = await peerId.privKey.sign(signData)
104+
105+
return new Envelope({
106+
peerId,
107+
payloadType,
108+
payload,
109+
signature
110+
})
111+
}
112+
113+
// ConsumeEnvelope unmarshals a serialized Envelope and validates its
114+
// signature using the provided 'domain' string. If validation fails, an error
115+
// is returned, along with the unmarshalled envelope so it can be inspected.
116+
//
117+
// On success, ConsumeEnvelope returns the Envelope itself, as well as the inner payload,
118+
// unmarshalled into a concrete Record type. The actual type of the returned Record depends
119+
// on what has been registered for the Envelope's PayloadType (see RegisterType for details).
120+
exports.openAndCertify = async (data, domain) => {
121+
const envelope = await unmarshalEnvelope(data)
122+
await envelope.validate(domain)
123+
124+
return envelope
125+
}
126+
127+
/**
128+
* Helper function that prepares a buffer to sign or verify a signature.
129+
* @param {string} domain
130+
* @param {number} payloadType
131+
* @param {Buffer} payload
132+
* @return {Buffer}
133+
*/
134+
const createSignData = (domain, payloadType, payload) => {
135+
// TODO: this should be compliant with the spec!
136+
const domainBuffer = Buffer.from(domain)
137+
const payloadTypeBuffer = Buffer.from(payloadType.toString())
138+
139+
return Buffer.concat([domainBuffer, payloadTypeBuffer, payload])
140+
}
141+
142+
/**
143+
* Unmarshal a serialized Envelope protobuf message.
144+
* @param {Buffer} data
145+
* @return {Envelope}
146+
*/
147+
const unmarshalEnvelope = async (data) => {
148+
const envelopeData = Protobuf.decode(data)
149+
const peerId = await PeerId.createFromPubKey(envelopeData.public_key)
150+
151+
return new Envelope({
152+
peerId,
153+
payloadType: envelopeData.payload_type,
154+
payload: envelopeData.payload,
155+
signature: envelopeData.signature
156+
})
157+
}

src/record-manager/index.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'use strict'
2+
3+
const debug = require('debug')
4+
const log = debug('libp2p:record-manager')
5+
log.error = debug('libp2p:record-manager:error')
6+
7+
const Envelope = require('./envelope')
8+
const PeerRecord = require('./peer-record')
9+
10+
/**
11+
* Responsible for managing the node signed peer record.
12+
* The record is generated on start and should be regenerated when
13+
* the public addresses of the peer change.
14+
*/
15+
class RecordManager {
16+
/**
17+
* @constructor
18+
* @param {Libp2p} libp2p
19+
*/
20+
constructor (libp2p) {
21+
this.libp2p = libp2p
22+
this._signedPeerRecord = undefined // TODO: map for multiple domains?
23+
}
24+
25+
/**
26+
* Start record manager. Compute current peer record and monitor address changes.
27+
* @return {void}
28+
*/
29+
async start () {
30+
const peerRecord = new PeerRecord({
31+
peerId: this.libp2p.peerId,
32+
multiaddrs: this.libp2p.multiaddrs
33+
})
34+
35+
this._signedPeerRecord = await Envelope.seal(peerRecord, this.libp2p.peerId)
36+
37+
// TODO: listen for address changes on AddressManager
38+
}
39+
40+
/**
41+
* Get signed peer record envelope.
42+
* @return {Envelope}
43+
*/
44+
getPeerRecordEnvelope () {
45+
// TODO: create here if not existing?
46+
return this._signedPeerRecord
47+
}
48+
}
49+
50+
module.exports = RecordManager
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict'
2+
3+
// const { Buffer } = require('buffer')
4+
const multicodec = require('multicodec')
5+
6+
// The domain string used for peer records contained in a Envelope.
7+
module.exports.ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record'
8+
9+
// The type hint used to identify peer records in a Envelope.
10+
// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv
11+
// with name "libp2p-peer-record"
12+
// TODO
13+
// const b = Buffer.aloc(2)
14+
// b.writeInt16BE(multicodec.LIBP2P_PEER_RECORD)
15+
// module.exports.ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = b
16+
17+
// const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Buffer.aloc(2)
18+
module.exports.ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = multicodec.LIBP2P_PEER_RECORD

0 commit comments

Comments
 (0)