All files HdPrivateKey.ts

100% Statements 91/91
100% Branches 35/35
100% Functions 15/15
100% Lines 90/90

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 3981x 1x 1x 1x 1x 1x 1x   1x   1x 1x 1x 1x             1x                                                     55x       55x 1x       54x 54x 149x     149x 149x         149x 4x     145x       50x   14x 12x     2x 1x       1x         50x     50x 133x     50x                                   81x   81x 81x 81x 81x 81x 81x 81x 81x                                                                     22x 22x 1x   21x                                                                                           91x                 91x   79x   6x   6x                 2x             143x 141x   143x                             143x 143x 143x 143x 143x   143x     143x 89x 89x 89x       54x 54x     143x 143x 143x   143x 143x   143x                         2x 1x   2x                                               43x 43x 43x 43x 43x 43x 43x 43x               1x                   3x                                                     49x               1x               1x      
import * as crypto from "@node-lightning/crypto";
import { BufferWriter } from "@node-lightning/bufio";
import { BitcoinError } from "./BitcoinError";
import { BitcoinErrorCode } from "./BitcoinErrorCode";
import { HdKeyCodec } from "./HdKeyCodec";
import { HdKeyType } from "./HdKeyType";
import { HdPublicKey } from "./HdPublicKey";
import { Network } from "./Network";
import { PrivateKey } from "./PrivateKey";
 
const MAX_INDEX = 0xffffffff;
const HARDENED_INDEX = 0x80000000;
const BIP49_PURPOSE = 0x80000031; // 49'
const BIP84_PURPOSE = 0x80000054; // 84'
 
/**
 * Represnts a hierarchical deterministic extended private key as defined
 * in BIP32. This class contains helper methods to derive child keys and
 * manage derivation.
 */
export class HdPrivateKey {
    /**
     * Constructs an extended private key from a derivation path by
     * performing a sequence of private key derivations.
     *
     * For example: `m/0'/1`
     *
     * * Must start at the master key `m`
     * * Hardened indices include a tick, `'`, eg: `0'` or `100'`
     * * Each level is split with a `/`
     *
     * Derivation requires the seed, network, and type to correctly
     * derive the private key.
     *
     * @param path string path
     * @param seed 32-byte seed
     * @param network network that the private key belongs to
     * @param type type of HD key (x, y, z) which defaults to x when a
     * BIP49 or BIP84 path is not detected
     * @returns the extended private key at the defined path
     */
    public static fromPath(
        path: string,
        seed: Buffer,
        network: Network,
        type?: HdKeyType,
    ): HdPrivateKey {
        const parts = path.split("/");
 
        // verify that we start with 'm' and that there are at most 255
        // sub-parts
        if (parts[0] !== "m" || parts.length > 255) {
            throw new BitcoinError(BitcoinErrorCode.InvalidHdPath, path);
        }
 
        // calculate the nums before we do anything else
        const nums: number[] = [];
        for (let i = 1; i < parts.length; i++) {
            const part = parts[i];
 
            // extract number
            const hardened = part.endsWith("'");
            const num = hardened
                ? HARDENED_INDEX + Number(part.substring(0, part.length - 1))
                : Number(part);
 
            // validate path was correct
            if (isNaN(num) || num < 0 || num > MAX_INDEX || (!hardened && num >= HARDENED_INDEX)) {
                throw new BitcoinError(BitcoinErrorCode.InvalidHdPath, path);
            }
 
            nums.push(num);
        }
 
        // attempt to detect the type if one was not supplied...
        if (!type) {
            // purpose is 84', type is z
            if (nums[0] && nums[0] === BIP84_PURPOSE) {
                type = HdKeyType.z;
            }
            // purpose is 49', type is y
            else if (nums[0] && nums[0] === BIP49_PURPOSE) {
                type = HdKeyType.y;
            }
            // otherwise it's x
            else {
                type = HdKeyType.x;
            }
        }
 
        // generate the master key
        let key = HdPrivateKey.fromSeed(seed, network, type);
 
        // perform derivations from the master
        for (const num of nums) {
            key = key.derive(num);
        }
 
        return key;
    }
 
    /**
     * Generates the master extended private key from the seed.
     *
     * @remarks
     * The master key has a depth of 0 and an parent fingerprint of
     * 0x00000000. The master key is generated from the HMAC-SHA512
     * using the key "Bitcoin seed" and the 32-byte seed as the data
     * part.
     *
     * @param seed 32-byte seed
     * @param network network the key belongs to
     * @param type HD key type (x, y, z)
     * @returns master extended pivate key
     */
    public static fromSeed(seed: Buffer, network: Network, type = HdKeyType.x): HdPrivateKey {
        const l = crypto.hmac(Buffer.from("Bitcoin seed"), seed, "sha512");
 
        const key = new HdPrivateKey();
        key.type = type;
        key.depth = 0;
        key.number = 0;
        key.parentFingerprint = Buffer.from([0, 0, 0, 0]);
        key.chainCode = l.slice(32);
        key.privateKey = new PrivateKey(l.slice(0, 32), network);
        return key;
    }
 
    /**
     * Decodes an extended private key from the serialization format
     * defined in BIP32.
     *
     * For example:
     * xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi
     *
     * @remarks
     *
     * The value uses a prefix of xprv, yprv, or zprv and is Base58Check.
     *
     * ```
     * The format includes:
     * [4 byte]: version
     * [1 byte]: depth
     * [4 byte]: parent fingerprint
     * [4 byte]: number
     * [32 byte]: chaincode
     * [33 byte]: key
     * ```
     *
     * The 33-byte key values uses a 0x00 prefix plus the 32-byte private
     * key.
     *
     * @param input encoded input
     *
     * @throws {@link BitcoinError} throws when there is an invalid
     * encoding, bad checksum, or if you attempt to decode a public key.
     *
     * @returns an instance of the extended private key
     */
    public static decode(input: string): HdPrivateKey {
        const result = HdKeyCodec.decode(input);
        if (!(result instanceof HdPrivateKey)) {
            throw new BitcoinError(BitcoinErrorCode.InvalidHdPrivateKey, input);
        } else {
            return result;
        }
    }
 
    /**
     * The type of extended key. This ensures that xprv, yprv, and
     * zprv values are not used in the same path.
     */
    public type: HdKeyType;
 
    /**
     * The depth of the derivation path. Depth of 0 is the master key.
     * Maximum depth is 255 since this is encoded using a single byte.
     */
    public depth: number;
 
    /**
     * The parents fingerprint which is the first 4-bytes of the hash160
     * of the compressed public key. The fingerprint of the parent only
     * serves as a fast way to detect parent and child keys and software
     * must be willing to deal with collisions.
     */
    public parentFingerprint: Buffer;
 
    /**
     * Specifies the child key number. Values between 0 to 2^31-1 are
     * non-hardened. Values between 2^31 to 2^32-1 are hardened.
     */
    public number: number;
 
    /**
     * The extended private key's chaincode
     */
    public chainCode: Buffer;
 
    /**
     * The underlying private key instance for extended private key
     */
    public privateKey: PrivateKey;
 
    private _fingerprint: Buffer;
 
    /**
     * The network the extended private key belongs to
     */
    public get network(): Network {
        return this.privateKey.network;
    }
 
    /**
     * The numeric version of the extended private key. This value is
     * determiend by the network and is used to encode a prefix when
     * the extended private key is encoded as a string.
     */
    public get version(): number {
        switch (this.type) {
            case HdKeyType.x:
                return this.network.xprvVersion;
            case HdKeyType.y:
                return this.network.yprvVersion;
            case HdKeyType.z:
                return this.network.zprvVersion;
        }
    }
 
    /**
     * Returns true when the key is a hardened key. A key is hardened
     * when it has an index between 2^31 and 2^32-1
     */
    public get isHardened(): boolean {
        return this.number >= HARDENED_INDEX;
    }
 
    /**
     * Lazy loads the fingerprint of the current extended private key
     */
    public get fingerprint(): Buffer {
        if (!this._fingerprint) {
            this._fingerprint = crypto.hash160(this.privateKey.toPubKey(true).toBuffer());
        }
        return this._fingerprint;
    }
 
    /**
     * Derives the child private key at the specified index. This
     * method is capable of deriving both hardened and non-hardened
     * child keys.
     *
     * @remarks
     *
     * @param i number of key to derive
     * @throws if this generates an invalid key either because the tweak
     * was invalid or the resulting private key is invalid.
     */
    public derive(i: number): HdPrivateKey {
        const result = new HdPrivateKey();
        result.type = this.type;
        result.depth = this.depth + 1;
        result.number = i;
        result.parentFingerprint = Buffer.from(this.fingerprint.slice(0, 4));
 
        const data = new BufferWriter(Buffer.alloc(37));
 
        // hardened
        if (i >= HARDENED_INDEX) {
            data.writeUInt8(0);
            data.writeBytes(this.privateKey.toBuffer());
            data.writeUInt32BE(i);
        }
        // normal child
        else {
            data.writeBytes(this.privateKey.toPubKey(true).toBuffer());
            data.writeUInt32BE(i);
        }
 
        const l = crypto.hmac(this.chainCode, data.toBuffer(), "sha512");
        const ll = l.slice(0, 32);
        const lr = l.slice(32);
 
        result.privateKey = this.privateKey.tweakAdd(ll);
        result.chainCode = lr;
 
        return result;
    }
 
    /**
     * Derives a hardened child key at the specified index. This method
     * simplifies derivation of hardened keys be treating the argument
     * as a hardened index. For example: `.deriveHardened(0)` derives
     * `0'` at index `0x80000000`.
     * @param i index of hardened key
     * @throws if this generates an invalid key either because the tweak
     * was invalid or the resulting private key is invalid.
     */
    public deriveHardened(i: number): HdPrivateKey {
        if (i < HARDENED_INDEX) {
            i = i + HARDENED_INDEX;
        }
        return this.derive(i);
    }
 
    /**
     * Constructs the corresponding {@link HdPublicKey}.
     *
     * The derivation is defined in BIP32 using HMAC-SHA512
     * {@link https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki}
     *
     * The derivation uses the parent's chaincode as the `key`. Then uses
     * for the `data`:
     *
     * * non-hardened: `parent_pub_key || i`
     * * hardened: `0x00 || parent_priv_key || i`
     *
     * As such the data is always 37-bytes.
     *
     * The resulting 64-bytes are split where where the left half is
     * used to tweakAdd against the parent private key. The right half
     * is the child's chain_code.
     *
     * @returns The corresponding extended public key
     */
    public toPubKey(): HdPublicKey {
        const result = new HdPublicKey();
        result.type = this.type;
        result.depth = this.depth;
        result.number = this.number;
        result.parentFingerprint = Buffer.from(this.parentFingerprint);
        result.chainCode = Buffer.from(this.chainCode);
        result.publicKey = this.privateKey.toPubKey(true);
        return result;
    }
 
    /**
     * Returns the compressed WIF encoding
     * @returns
     */
    public toWif(): string {
        return this.privateKey.toWif(true);
    }
 
    /**
     * Returns the address encoded according to the type of HD key.
     * For x-type this returns a base58 encoded P2PKH address.
     * For y-type this returns a base58 encoded P2SH-P2WPKH address.
     * For z-type this returns a bech32 encoded P2WPKH address.
     */
    public toAddress(): string {
        return this.toPubKey().toAddress();
    }
 
    /**
     * Encodes the {@link HdPrivateKey} according to BIP32.
     *
     * For example:
     * xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi
     *
     * @remarks
     * The value uses a prefix of xprv, yprv, or zprv and is Base58Check
     * encoded.
     *
     * The format includes:
     * ```
     * [4 byte]: version
     * [1 byte]: depth
     * [4 byte]: parent fingerprint
     * [4 byte]: number
     * [32 byte]: chaincode
     * [33 byte]: key
     * ```
     *
     * For private keys, the 33-byte key value is prefixed with 0x00.
     * @returns Base58Check encoded extended private key
     */
    public encode(): string {
        return HdKeyCodec.encode(this);
    }
 
    /**
     * Returns a Buffer of the underlying private key encoded as a big
     * endian integer. This is sugar for `key.privateKey.toBuffer()`.
     */
    public toBuffer(): Buffer {
        return this.privateKey.toBuffer();
    }
 
    /**
     * Returns a hex string of the underlying private key. This is sugar
     * for `key.privateKey.toHex()`.
     */
    public toHex(): string {
        return this.privateKey.toHex();
    }
}