BSV blockchainBSV blockchain

How keys and identity work

On the BSV blockchain, a private key proves control. It signs the inputs that spend an output and the messages an app sends, and the matching public key lets anyone check those signatures. A wallet holds the keys for your app. You work with them when you derive a key for another party, identify a user or debug a failed signature. By the end of this page you can derive a key for a counterparty with ProtoWallet and recognize a user by their identity key.

The examples use @bsv/sdk 4.0.1 and run with Node.js. Install it with npm install @bsv/sdk@4.0.1, save each example as an .mjs file and run it with node. How the BSV blockchain stack fits together shows where the wallet sits.

Private keys, public keys and addresses

A private key is a 256 bit number, and the public key and the address are computed from it.

From a private key to an address

Select Private key, Public key, hash160SHA-256 followed by RIPEMD-160 of the public key and Address in turn to see what each one is and how it is made, then switch between Testnet and Mainnet to see what changes in the address.

Network
Made by
Computed from the private key on the secp256k1 curve, toPublicKey(), stored compressed
You can
Share it. Anyone can check your signatures with it.

Public key, 33 bytes. Computed from the private key on the secp256k1 curve, toPublicKey(), stored compressed. Share it. Anyone can check your signatures with it.

Sign and verify in code

This example creates a key pair, signs a message and checks the signature, then prints the hash160 of the public key.

Each example generates a new random private key on every run, only to try the code. Never put a private key that holds value in code, and never commit one to version control.

keys.mjs
import { PrivateKey, Hash, Utils } from '@bsv/sdk'

const privateKey = PrivateKey.fromRandom()
const publicKey = privateKey.toPublicKey()

console.log('public key:', publicKey.toString())
console.log('address:', publicKey.toAddress('testnet'))

const message = Utils.toArray('Hi John', 'utf8')
const signature = privateKey.sign(message)
console.log('verifies:', publicKey.verify(message, signature))
console.log('changed message verifies:', publicKey.verify(Utils.toArray('Hi Eve', 'utf8'), signature))
console.log('another public key verifies:', PrivateKey.fromRandom().toPublicKey().verify(message, signature))

console.log('hash160:', Utils.toHex(Hash.hash160(publicKey.encode(true))))

The signature verifies for the message it signed with the matching public key, and fails for a changed message or for another public key:

public key: 0366ef25ae5f614c870da7ed6a601bc03a32f910015752306414bfdbc1afe9f579
address: mmEyZENMwGN7MQxj1dAH8Y5gNezGvdHJHo
verifies: true
changed message verifies: false
another public key verifies: false
hash160: 3ecb270ad7f2875dd75b0f721ef08368fc414247

How Script works shows how the network checks the public key and signature that spend an output locked to that hash.

Hash functions

@bsv/sdk has Hash.sha256 (32 bytes), Hash.ripemd160 (20 bytes), Hash.hash160 and Hash.hash256, which is SHA-256 applied twice.

Derived keys

An app that signs everything with one key ties all its activity to that key. BRC-42The standard for deriving a separate key for each pair of parties gives two parties a way to derive a separate key for each other, and for each purpose, from keys they already have.

How two parties derive a key

Each party keeps a master private key and shares the master public key. The two agree on an invoice number, any string that names the purpose, such as order 1042. Both get the same shared secret through ECDHElliptic curve Diffie-Hellman, a way for two parties to compute the same secret from their own private key and the other's public key and run an HMACHash based message authentication code over the invoice number with it. The owner adds the result to the master private key to get the child private key. The other party adds it to the owner’s master public key to get the matching child public key.

Press Step to follow Jane and John to the same child key, then switch to Another invoice number or Another private key and run it again to watch the check fail.

John derives the key with

Jane

Jane master private key
John public key

John

John master private key
Jane public key
1 of 5

Jane and John each hold a master private key and know the other one's public key. They agree on the invoice number "order 1042".

Step 1 of 5. Jane and John each hold a master private key and know the other one's public key. They agree on the invoice number "order 1042".

Derive keys in code

Jane derives a private key for John from his public key and signs with it. John derives the matching public key from hers and checks the signature, then the example repeats the derivation with another invoice number and with another private key.

derive.mjs
import { PrivateKey, Utils } from '@bsv/sdk'

const jane = PrivateKey.fromRandom()
const john = PrivateKey.fromRandom()
const invoiceNumber = 'order 1042'

const janeChild = jane.deriveChild(john.toPublicKey(), invoiceNumber)
const signature = janeChild.sign(Utils.toArray('Hi John', 'utf8'))

const janeChildPublic = jane.toPublicKey().deriveChild(john, invoiceNumber)

console.log('keys match:', janeChild.toPublicKey().toString() === janeChildPublic.toString())
console.log('John verifies:', janeChildPublic.verify(Utils.toArray('Hi John', 'utf8'), signature))

const other = jane.toPublicKey().deriveChild(john, 'order 1043')
console.log('other invoice, same key:', other.toString() === janeChildPublic.toString())

const eve = PrivateKey.fromRandom()
const eveGuess = jane.toPublicKey().deriveChild(eve, invoiceNumber)
console.log('Eve verifies:', eveGuess.verify(Utils.toArray('Hi John', 'utf8'), signature))
keys match: true
John verifies: true
other invoice, same key: false
Eve verifies: false

John never sees Jane’s private key, and each pair of parties has its own set of derived keys. This differs from BIP32The standard for hierarchical wallets that derive child keys from one master key, where anyone holding an extended public key can derive its non hardened public child keys. The invoice number is not secret. What the derivation needs is the shared secret.

How a wallet organizes derived keys

BRC-43The standard format for invoice numbers: a security level, a protocol name and a key ID gives the invoice number a format that a wallet can enforce, <security level>-<protocol name>-<key ID>, for example 2-order receipts-1042. The security level and the counterparty decide which key the wallet derives and what it asks the user to approve. ProtoWallet in @bsv/sdk does the derivation and checks the names through its KeyDeriver. BRC-43 leaves the approval prompts to the wallet. The BRC-100 Wallet Interface covers the wallet calls for keys and encryption.

Build an invoice number

Move the Security level from 0 to 2 and pick a Counterparty to see what each one means, then edit the Protocol name and the Key ID to watch the invoice number change. Try the name order receipts protocol or a name with fewer than five characters to see a check fail.

Invoice number

2-order receipts-1042

Security level

Checks of KeyDeriver

  • At least 5 characters, passes
  • No double spaces, passes
  • Does not end in " protocol", passes
  • Letters, numbers and spaces only, passes
  • At most 400 characters, passes
  • Key ID has at least 1 character, passes
Counterparty

The wallet needs their identity public key. They derive the matching key with yours.

The wallet asks the user

Once for the app, the protocol and each counterparty.

Invoice number 2-order receipts-1042. All checks pass. Counterparty Another party. Once for the app, the protocol and each counterparty.

Sign and encrypt with a wallet

Two ProtoWallet instances stand in for the wallets of Jane and John. Jane signs and encrypts a message for John under the invoice number from the builder, and John verifies and decrypts it.

wallet.mjs
import { PrivateKey, ProtoWallet, Utils } from '@bsv/sdk'

const jane = new ProtoWallet(PrivateKey.fromRandom())
const john = new ProtoWallet(PrivateKey.fromRandom())

const janeIdentity = (await jane.getPublicKey({ identityKey: true })).publicKey
const johnIdentity = (await john.getPublicKey({ identityKey: true })).publicKey

// protocolID is [security level, protocol name], and the key ID picks one key inside it.
const protocolID = [2, 'order receipts']
const keyID = '1042'
const data = Utils.toArray('Order 1042 received', 'utf8')

const { signature } = await jane.createSignature({ data, protocolID, keyID, counterparty: johnIdentity })
const { valid } = await john.verifySignature({ data, signature, protocolID, keyID, counterparty: janeIdentity })
console.log('John verifies:', valid)

for (const counterparty of ['self', 'anyone', johnIdentity]) {
  const { publicKey } = await jane.getPublicKey({ protocolID, keyID, counterparty })
  console.log(counterparty === johnIdentity ? 'John' : counterparty, publicKey.slice(0, 12) + '...')
}

const { ciphertext } = await jane.encrypt({ plaintext: data, protocolID, keyID, counterparty: johnIdentity })
const { plaintext } = await john.decrypt({ ciphertext, protocolID, keyID, counterparty: janeIdentity })
console.log('John decrypts:', Utils.toUTF8(plaintext))
John verifies: true
self 03e081bd8e89...
anyone 03bed2a7e407...
John 0278068d14d6...
John decrypts: Order 1042 received

A signature made under one protocol name or key ID does not verify under another. ProtoWallet rejects an invalid name, so order receipts protocol throws No need to end your protocol name with " protocol". PrivateKey.deriveChild does not run these checks, it takes any string.

Identity keys and mutual authentication

The identity key is the root public key of the wallet. It stays the same across calls and differs from the keys derived for protocols. An app reads it with getPublicKey({ identityKey: true }) and uses it to recognize a user.

A request with and without authentication

Two parties prove their identity keys to each other in a handshake. BRC-103The standard for mutual authentication between peers defines this exchange between peers, and BRC-104The standard that binds BRC-103 to HTTP binds it to HTTP. AuthFetch in @bsv/sdk is the client, and @bsv/auth-express-middleware is the server. Follow a request from the app to the server with Step, then switch to A plain fetch to see the server turn it away. Authenticate users with their wallet walks through the setup.

The app sends the request with

App

wallet
AuthFetch.fetch(url)

Express server

createAuthMiddleware
1 of 4

The app has a wallet and calls AuthFetch with the URL of the server. The server runs the auth middleware.

Step 1 of 4. The app has a wallet and calls AuthFetch with the URL of the server. The server runs the auth middleware.

What the identity covers

In the BRC-104 v0.1 binding, as the ts-stack identity page describes it, the signature covers some parts of a request and not others:

CoveredNot covered
Method, path and queryHost header
Declared signed headers and bodyCookies and most other headers

Authorize with the authenticated identity key and the covered parts only. BRC-31The earlier authentication handshake, replaced by BRC-103 and BRC-104 is historical guidance, not the current HTTP contract.

Certificates

A certifier signs a certificate that binds fields to the identity key of a user, and the fields are encrypted. The certificate verifies, and it no longer verifies if a field changes.

To learn more about keys and identity on the BSV blockchain, review these articles: