chainside / btcnodejs

A Nodejs SegWit-compliant library which provides tools to handle Bitcoin data structures in a simple fashion.
https://www.chainside.net
GNU Lesser General Public License v3.0
37 stars 13 forks source link

Segwit bc1 address #16

Closed random9brat closed 2 years ago

random9brat commented 2 years ago

is there any simple method of creating bc1... public address from private key within btcnodejs ? If so could please anyone give me a little push since im new...

d0ze commented 2 years ago

Hi, what you are looking for are P2wpkh scripts. Given a private key

> privKey = btc.Privatekey.fromBip32('xprvA1qpeqQXYkScHFt8KjA24PUsTGgkZNJQGmDm46b2Ha8rBLEo4f8Jy4uz4BAKirfv5MkwyjbuFLexaNuymFstTYsoZPuT3vSsDobP1TxmWsf')
Privatekey {
  body: ByteBuffer {
    buffer: <Buffer f4 5c bd 8b e5 95 16 1c 7f d5 0d 6f e4 a3 08 41 d9 24 8b 1d b8 0b 6e 77 07 8b 72 61 e2 03 1a f0>,
    offset: 0,
    markedOffset: -1,
    limit: 32,
    littleEndian: false,
    noAssert: true
  }
}

You can obtain the corresponding public key instance

> pubKey = privKey.getPublic()
Publickey {
  type: 'even',
  compressed: ByteBuffer {
    buffer: <Buffer 02 26 ee b6 60 c6 9f 18 63 14 bd 58 82 cd 0d cd 2c ce 91 3e 05 55 66 39 e5 db fb ad c4 b0 df aa 74>,
    offset: 0,
    markedOffset: -1,
    limit: 33,
    littleEndian: false,
    noAssert: true
  },
  uncompressed: ByteBuffer {
    buffer: <Buffer 04 26 ee b6 60 c6 9f 18 63 14 bd 58 82 cd 0d cd 2c ce 91 3e 05 55 66 39 e5 db fb ad c4 b0 df aa 74 69 b8 cf 79 0a c1 2b be 50 05 6b d0 fc 8e d6 9a 2b ... 15 more bytes>,
    offset: 65,
    markedOffset: -1,
    limit: 65,
    littleEndian: false,
    noAssert: false
  }
}

With a PublicKey instance, you can construct a script of any type defined in the library. For p2wpkh (v0) scripts, you can do as following

> p2wpkhScript = new btc.P2wpkhV0Script(public)
P2wpkhV0Script {
  body: ByteBuffer {
    buffer: <Buffer 00 14 1f e1 05 c5 28 2f f9 78 57 84 bc 30 d1 50 0f 28 97 fb d1 ea>,
    offset: 22,
    markedOffset: -1,
    limit: 22,
    littleEndian: false,
    noAssert: false
  },
  type: 'p2wpkh',
  pubkeyhash: ByteBuffer {
    buffer: <Buffer 1f e1 05 c5 28 2f f9 78 57 84 bc 30 d1 50 0f 28 97 fb d1 ea>,
    offset: 0,
    markedOffset: -1,
    limit: 20,
    littleEndian: false,
    noAssert: true
  }
}

To obtain the bech32 representation of the address, you can retrieve an Address instance from the script instance, and then get the bech32 form of the addresss

> p2wpkhScript.getAddress().toBech32()
'bc1qrlsst3fg9luhs4uyhscdz5q09ztlh502wwud94'