/
script.rb
98 lines (77 loc) · 2.54 KB
/
script.rb
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
# frozen_string_literal: true
module CKB
module Types
class Script
attr_accessor :code_hash, :args, :hash_type
# @param code_hash [String]
# @param args [String]
# @param hash_type [String] data/type
def initialize(code_hash:, args:, hash_type: "data")
@code_hash = code_hash
@args = args
@hash_type = hash_type
validate_code_hash!
validate_args!
validate_hash_type!
end
# @return [Integer] Byte
def calculate_bytesize
bytesize = 1
bytesize += Utils.hex_to_bin(@code_hash).bytesize if @code_hash
bytesize += Utils.hex_to_bin(args).bytesize if args
bytesize
end
def to_h
{
code_hash: @code_hash,
args: @args,
hash_type: @hash_type
}
end
def self.from_h(hash)
return if hash.nil?
new(
code_hash: hash[:code_hash],
args: hash[:args],
hash_type: hash[:hash_type]
)
end
def compute_hash
script_serializer = CKB::Serializers::ScriptSerializer.new(self)
blake2b = CKB::Blake2b.new
blake2b << Utils.hex_to_bin(script_serializer.serialize)
blake2b.hexdigest
end
def self.generate_lock(target_pubkey_blake160, secp_cell_type_hash, hash_type = "type")
new(
code_hash: secp_cell_type_hash,
args: target_pubkey_blake160,
hash_type: hash_type
)
end
def validate_code_hash!
raise EmptyCodeHashError, "CodeHash cannot be empty" unless has_code_hash?
raise InvalidHexStringError, "CodeHash is an invalid hex string" unless CKB::Utils.valid_hex_string?(code_hash)
if CKB::Utils.hex_to_bin(code_hash).size != 32
raise InvalidCodeHashSizeError, "CodeHash bytesize must equal to 32"
end
end
def validate_args!
raise InvalidHexStringError, "Args is an invalid hex string" if has_args? && !CKB::Utils.valid_hex_string?(args)
end
def has_code_hash?
!code_hash.nil? && !code_hash.empty?
end
def has_args?
!args.nil? && !args.empty?
end
def validate_hash_type!
raise InvalidHashTypeError, "Invalid hash type error" unless CKB::ScriptHashType::TYPES.include?(hash_type)
end
class EmptyCodeHashError < StandardError; end
class InvalidHexStringError < StandardError; end
class InvalidHashTypeError < StandardError; end
class InvalidCodeHashSizeError < StandardError; end
end
end
end