Class: BTC::Validation

Inherits:
Object
  • Object
show all
Defined in:
lib/btcruby/validation.rb

Instance Method Summary collapse

Constructor Details

#initialize(max_block_size: MAX_BLOCK_SIZE, min_coinbase_size: 2, max_coinbase_size: 100, max_money: MAX_MONEY) ⇒ Validation

Returns a new instance of Validation.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/btcruby/validation.rb', line 14

def initialize(
    max_block_size: MAX_BLOCK_SIZE,
    min_coinbase_size: 2,
    max_coinbase_size: 100,
    max_money: MAX_MONEY
  )
  @max_block_size = max_block_size
  @min_coinbase_size = min_coinbase_size
  @max_coinbase_size = max_coinbase_size
  @max_money = max_money
end

Instance Method Details

#check_money_range(value) ⇒ Object



79
80
81
# File 'lib/btcruby/validation.rb', line 79

def check_money_range(value)
  value >= 0 && value <= @max_money
end

#check_transaction(tx, state) ⇒ Object



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
# File 'lib/btcruby/validation.rb', line 26

def check_transaction(tx, state)
  # Basic checks that don't depend on any context
  if tx.inputs.empty?
    return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty")
  end
  if tx.outputs.empty?
    return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty")
  end

  # Size limits
  if tx.data.bytesize > @max_block_size
    return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize")
  end

  # Check for negative or overflow output values
  tx.outputs.inject(0) do |total, txout|
    if txout.value < 0
      return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative")
    end
    if txout.value > @max_money
      return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge")
    end
    total += txout.value
    if !check_money_range(total)
      return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge")
    end
    total
  end

  # Check for duplicate inputs
  used_outpoints = {} # outpoint => true
  tx.inputs.each do |txin|
    if used_outpoints[txin.outpoint]
      return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate")
    end
    used_outpoints[txin.outpoint] = true
  end

  if tx.coinbase?
    cb_size = tx.inputs[0].coinbase_data.bytesize
    if cb_size < @min_coinbase_size || cb_size > @max_coinbase_size
      return state.DoS(100, false, REJECT_INVALID, "bad-cb-length")
    end
  else
    tx.inputs.each do |txin|
      if txin.outpoint.null?
        return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null")
      end
    end
  end
  return true
end