Class: Zold::Patch

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/patch.rb

Overview

A patch

Instance Method Summary collapse

Constructor Details

#initialize(log: Log::Quiet.new) ⇒ Patch

Returns a new instance of Patch.



34
35
36
# File 'lib/zold/patch.rb', line 34

def initialize(log: Log::Quiet.new)
  @log = log
end

Instance Method Details

#join(wallet) ⇒ Object



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
# File 'lib/zold/patch.rb', line 43

def join(wallet)
  if @id.nil?
    @id = wallet.id
    @key = wallet.key
    @txns = wallet.txns
    @log.debug("The baseline: #{@txns.count} transactions, the balance is #{wallet.balance}")
    @network = wallet.network
  end
  if wallet.network != @network
    raise "The wallet is from a different network '#{wallet.network}', ours is '#{@network}'"
  end
  raise 'Public key mismatch' if wallet.key != @key
  raise "Wallet ID mismatch: #{@id} != #{wallet.id}" if wallet.id != @id
  negative = @txns.select { |t| t.amount.negative? }
  max = negative.empty? ? 0 : negative.max_by(&:id).id
  wallet.txns.each do |txn|
    next if @txns.find { |t| t == txn }
    if txn.amount.negative?
      if txn.id <= max
        @log.debug("Transaction ID is less than max #{max}: #{txn.to_text}")
        next
      end
      if @txns.find { |t| t.id == txn.id }
        @log.debug("Transaction ##{txn.id} already exists: #{txn.to_text}")
        next
      end
      if !@txns.empty? && @txns.map(&:amount).inject(&:+) < txn.amount
        @log.debug("Transaction ##{txn.id} attempts to make the balance negative: #{txn.to_text}")
        next
      end
      unless Signature.new.valid?(@key, wallet.id, txn)
        @log.debug("Invalid RSA signature at transaction ##{txn.id} of #{wallet.id}: #{txn.to_text}")
        next
      end
    elsif !txn.sign.nil? && !txn.sign.empty?
      @log.debug("RSA signature is redundant at ##{txn.id} of #{wallet.id}: #{txn.to_text}")
      next
    end
    @log.debug("Merged on top: #{txn.to_text}")
    @txns << txn
  end
end

#save(file, overwrite: false) ⇒ Object

Returns TRUE if the file was actually modified



87
88
89
90
91
92
93
94
95
96
# File 'lib/zold/patch.rb', line 87

def save(file, overwrite: false)
  raise 'You have to join at least one wallet in' if @id.nil?
  before = ''
  before = AtomicFile.new(file).read if File.exist?(file)
  wallet = Wallet.new(file)
  wallet.init(@id, @key, overwrite: overwrite, network: @network)
  @txns.each { |t| wallet.add(t) }
  after = AtomicFile.new(file).read
  before != after
end

#to_sObject



38
39
40
41
# File 'lib/zold/patch.rb', line 38

def to_s
  return 'empty' if @id.nil?
  "#{@txns.count} txns"
end