-
Notifications
You must be signed in to change notification settings - Fork 0
/
flow_checker.go
49 lines (39 loc) · 1.24 KB
/
flow_checker.go
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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package djtx
import (
"errors"
"github.com/lasthyphen/beacongo/ids"
"github.com/lasthyphen/beacongo/utils/math"
"github.com/lasthyphen/beacongo/utils/wrappers"
)
var errInsufficientFunds = errors.New("insufficient funds")
type FlowChecker struct {
consumed, produced map[ids.ID]uint64
errs wrappers.Errs
}
func NewFlowChecker() *FlowChecker {
return &FlowChecker{
consumed: make(map[ids.ID]uint64),
produced: make(map[ids.ID]uint64),
}
}
func (fc *FlowChecker) Consume(assetID ids.ID, amount uint64) { fc.add(fc.consumed, assetID, amount) }
func (fc *FlowChecker) Produce(assetID ids.ID, amount uint64) { fc.add(fc.produced, assetID, amount) }
func (fc *FlowChecker) add(value map[ids.ID]uint64, assetID ids.ID, amount uint64) {
var err error
value[assetID], err = math.Add64(value[assetID], amount)
fc.errs.Add(err)
}
func (fc *FlowChecker) Verify() error {
if !fc.errs.Errored() {
for assetID, producedAssetAmount := range fc.produced {
consumedAssetAmount := fc.consumed[assetID]
if producedAssetAmount > consumedAssetAmount {
fc.errs.Add(errInsufficientFunds)
break
}
}
}
return fc.errs.Err
}