Class: Sibit::Script

Inherits:
Object
  • Object
show all
Defined in:
lib/sibit/script.rb

Overview

Bitcoin Script parser.

Parses standard P2PKH and P2WPKH scripts to extract addresses.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2019-2026 Yegor Bugayenko

License

MIT

Constant Summary collapse

OP_0 =
0x00
OP_DUP =
0x76
OP_HASH160 =
0xa9
OP_EQUALVERIFY =
0x88
OP_CHECKSIG =
0xac

Instance Method Summary collapse

Constructor Details

#initialize(hex) ⇒ Script

Returns a new instance of Script.



26
27
28
# File 'lib/sibit/script.rb', line 26

def initialize(hex)
  @bytes = [hex].pack('H*').bytes
end

Instance Method Details

#address(network = :mainnet) ⇒ Object



30
31
32
33
34
# File 'lib/sibit/script.rb', line 30

def address(network = :mainnet)
  return p2wpkh_address(network) if p2wpkh?
  return p2pkh_address(network) if p2pkh?
  nil
end

#hash160Object



51
52
53
54
55
# File 'lib/sibit/script.rb', line 51

def hash160
  return @bytes[2, 20].pack('C*').unpack1('H*') if p2wpkh?
  return @bytes[3, 20].pack('C*').unpack1('H*') if p2pkh?
  nil
end

#p2pkh?Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
# File 'lib/sibit/script.rb', line 36

def p2pkh?
  @bytes.length == 25 &&
    @bytes[0] == OP_DUP &&
    @bytes[1] == OP_HASH160 &&
    @bytes[2] == 20 &&
    @bytes[23] == OP_EQUALVERIFY &&
    @bytes[24] == OP_CHECKSIG
end

#p2wpkh?Boolean

Returns:

  • (Boolean)


45
46
47
48
49
# File 'lib/sibit/script.rb', line 45

def p2wpkh?
  @bytes.length == 22 &&
    @bytes[0] == OP_0 &&
    @bytes[1] == 20
end