Skip to content

Instantly share code, notes, and snippets.

@mfornos
Last active February 19, 2024 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfornos/5150adb07b5de0d97d2e8e35702d7752 to your computer and use it in GitHub Desktop.
Save mfornos/5150adb07b5de0d97d2e8e35702d7752 to your computer and use it in GitHub Desktop.
Polkadot P2P Authority Discovery
  1. Get the identifiers of the current and next authority set from the Runtime API, e.g. using the RPC interface for a PoC.
const res = await api.call.authorityDiscoveryApi.authorities()
const authorities = res.toHuman().map(a => keyring.decodeAddress(a))

Reference: https://docs.rs/sp-authority-discovery/27.0.0/sp_authority_discovery/trait.AuthorityDiscoveryApi.html

  1. Load the protobuf DHT discovery types.
const disco = await protobuf.load(dirname(import.meta.url) + '/dht_disco-v2.proto')
const SignedAuthorityRecord = disco.lookupType('authority_discovery_v2.SignedAuthorityRecord')
  1. Resolve peer identities for the authorities.
for (const authKey of authorities) {
  const keyHash = crypto.createHash('sha256').update(authKey).digest()
  try {
    // find the key hash in the DHT
    for await (const res of this.dht.get(keyHash)) {
      if (res.type === 5) {
        // decode with the protobuf SignedAuthorityRecord type
        const rec = SignedAuthorityRecord.decode(res.value)
        // where 0x00 = no hash, 0x36 = id length
        const id = new Uint8Array([0, 36, ...rec.peerSignature.publicKey])
        const authorityPeerId = peerIdFromBytes(id)

        console.log('Found', authorityPeerId, authKey)
        // ...
      }
    }
  } // ...
}
  1. Have fun! (ಠ◡ಠ)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment