/
p2pk.js
56 lines (50 loc) · 1.21 KB
/
p2pk.js
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
import nimble from '@runonbitcoin/nimble'
import { Cast } from '../classes/cast.js'
import { signTx } from '../macros/index.js'
const { OP_CHECKSIG } = nimble.constants.opcodes
/**
* Pay to Public Key
*
* P2PK scripts are used to lock Bitcoin to a public key. The Bitcoin can later
* be unlocked using the corresponding private key.
*
* ## Lock params
*
* - `pubkey` - Public key
*
* ## Unlock params
*
* - `privkey` - Private key
*
* ## Examples
*
* ```
* P2PK.lock(1000, { pubkey })
*
* P2PK.unlock(utxo, { privkey })
* ```
*/
export class P2PK extends Cast {
init() {
if (this.mode === 'lock') validateLock(this.params)
if (this.mode === 'unlock') validateUnlock(this.params)
}
lockingScript({ pubkey }) {
this.script
.push(pubkey)
.push(OP_CHECKSIG)
}
unlockingScript({ privkey }) {
this.script.apply(signTx, [privkey])
}
}
function validateLock({ pubkey } = {}) {
if (!(pubkey && pubkey.point)) {
throw new Error('P2PK unlock must be created with valid `pubkey`')
}
}
function validateUnlock({ privkey } = {}) {
if (!(privkey && typeof privkey.toPublicKey === 'function')) {
throw new Error('P2PK unlock must be created with valid `privkey`')
}
}