11 log "github.com/sirupsen/logrus"
12 "github.com/bytom/vapor/errors"
13 "github.com/bytom/vapor/protocol/bc"
16 const desireUtxoCount = 5
18 // pre-define error types
20 ErrInsufficient = errors.New("reservation found insufficient funds")
21 ErrImmature = errors.New("reservation found immature funds")
22 ErrVoteLock = errors.New("Locked by the vote")
23 ErrReserved = errors.New("reservation found outputs already reserved")
24 ErrMatchUTXO = errors.New("can't find utxo with given hash")
25 ErrReservation = errors.New("couldn't find reservation")
28 // UTXO describes an individual account utxo.
39 ControlProgramIndex uint64
44 // reservation describes a reservation of a set of UTXOs
45 type reservation struct {
52 type utxoKeeper struct {
53 // `sync/atomic` expects the first word in an allocated struct to be 64-bit
54 // aligned on both ARM and x86-32. See https://goo.gl/zW7dgq for more details.
58 currentHeight func() uint64
60 unconfirmed map[bc.Hash]*UTXO
61 reserved map[bc.Hash]uint64
62 reservations map[uint64]*reservation
65 func newUtxoKeeper(f func() uint64, store AccountStore) *utxoKeeper {
69 unconfirmed: make(map[bc.Hash]*UTXO),
70 reserved: make(map[bc.Hash]uint64),
71 reservations: make(map[uint64]*reservation),
77 func (uk *utxoKeeper) AddUnconfirmedUtxo(utxos []*UTXO) {
81 for _, utxo := range utxos {
82 uk.unconfirmed[utxo.OutputID] = utxo
86 // Cancel canceling the reservation with the provided ID.
87 func (uk *utxoKeeper) Cancel(rid uint64) {
93 // ListUnconfirmed return all the unconfirmed utxos
94 func (uk *utxoKeeper) ListUnconfirmed() []*UTXO {
99 for _, utxo := range uk.unconfirmed {
100 utxos = append(utxos, utxo)
105 func (uk *utxoKeeper) RemoveUnconfirmedUtxo(hashes []*bc.Hash) {
107 defer uk.mtx.Unlock()
109 for _, hash := range hashes {
110 delete(uk.unconfirmed, *hash)
114 func (uk *utxoKeeper) Reserve(accountID string, assetID *bc.AssetID, amount uint64, useUnconfirmed bool, vote []byte, exp time.Time) (*reservation, error) {
116 defer uk.mtx.Unlock()
118 utxos, immatureAmount := uk.findUtxos(accountID, assetID, useUnconfirmed, vote)
119 optUtxos, optAmount, reservedAmount := uk.optUTXOs(utxos, amount)
120 if optAmount+reservedAmount+immatureAmount < amount {
121 return nil, ErrInsufficient
124 if optAmount+reservedAmount < amount {
126 return nil, ErrVoteLock
128 return nil, ErrImmature
131 if optAmount < amount {
132 return nil, ErrReserved
135 result := &reservation{
136 id: atomic.AddUint64(&uk.nextIndex, 1),
138 change: optAmount - amount,
142 uk.reservations[result.id] = result
143 for _, u := range optUtxos {
144 uk.reserved[u.OutputID] = result.id
149 func (uk *utxoKeeper) ReserveParticular(outHash bc.Hash, useUnconfirmed bool, exp time.Time) (*reservation, error) {
151 defer uk.mtx.Unlock()
153 if _, ok := uk.reserved[outHash]; ok {
154 return nil, ErrReserved
157 u, err := uk.findUtxo(outHash, useUnconfirmed)
162 if u.ValidHeight > uk.currentHeight() {
163 return nil, ErrImmature
166 result := &reservation{
167 id: atomic.AddUint64(&uk.nextIndex, 1),
171 uk.reservations[result.id] = result
172 uk.reserved[u.OutputID] = result.id
176 func (uk *utxoKeeper) cancel(rid uint64) {
177 res, ok := uk.reservations[rid]
182 delete(uk.reservations, rid)
183 for _, utxo := range res.utxos {
184 delete(uk.reserved, utxo.OutputID)
188 func (uk *utxoKeeper) expireWorker() {
189 ticker := time.NewTicker(1000 * time.Millisecond)
192 for now := range ticker.C {
193 uk.expireReservation(now)
197 func (uk *utxoKeeper) expireReservation(t time.Time) {
199 defer uk.mtx.Unlock()
201 for rid, res := range uk.reservations {
202 if res.expiry.Before(t) {
208 func (uk *utxoKeeper) findUtxos(accountID string, assetID *bc.AssetID, useUnconfirmed bool, vote []byte) ([]*UTXO, uint64) {
209 immatureAmount := uint64(0)
210 currentHeight := uk.currentHeight()
212 appendUtxo := func(u *UTXO) {
213 if u.AccountID != accountID || u.AssetID != *assetID || !bytes.Equal(u.Vote, vote) {
217 if u.ValidHeight > currentHeight {
218 immatureAmount += u.Amount
220 utxos = append(utxos, u)
224 UTXOs, err := uk.store.ListUTXOs()
226 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("utxoKeeper findUtxos fail on unmarshal utxo")
229 for _, UTXO := range UTXOs {
234 return utxos, immatureAmount
237 for _, u := range uk.unconfirmed {
240 return utxos, immatureAmount
243 func (uk *utxoKeeper) findUtxo(outHash bc.Hash, useUnconfirmed bool) (*UTXO, error) {
244 if u, ok := uk.unconfirmed[outHash]; useUnconfirmed && ok {
247 return uk.store.GetUTXO(outHash)
250 func (uk *utxoKeeper) optUTXOs(utxos []*UTXO, amount uint64) ([]*UTXO, uint64, uint64) {
251 //sort the utxo by amount, bigger amount in front
252 var optAmount, reservedAmount uint64
253 sort.Slice(utxos, func(i, j int) bool {
254 return utxos[i].Amount > utxos[j].Amount
257 //push all the available utxos into list
258 utxoList := list.New()
259 for _, u := range utxos {
260 if _, ok := uk.reserved[u.OutputID]; ok {
261 reservedAmount += u.Amount
267 optList := list.New()
268 for node := utxoList.Front(); node != nil; node = node.Next() {
269 //append utxo if we haven't reached the required amount
270 if optAmount < amount {
271 optList.PushBack(node.Value)
272 optAmount += node.Value.(*UTXO).Amount
276 largestNode := optList.Front()
277 replaceList := list.New()
278 replaceAmount := optAmount - largestNode.Value.(*UTXO).Amount
280 for ; node != nil && replaceList.Len() <= desireUtxoCount-optList.Len(); node = node.Next() {
281 replaceList.PushBack(node.Value)
282 if replaceAmount += node.Value.(*UTXO).Amount; replaceAmount >= amount {
283 optList.Remove(largestNode)
284 optList.PushBackList(replaceList)
285 optAmount = replaceAmount
290 //largestNode remaining the same means that there is nothing to be replaced
291 if largestNode == optList.Front() {
296 optUtxos := []*UTXO{}
297 for e := optList.Front(); e != nil; e = e.Next() {
298 optUtxos = append(optUtxos, e.Value.(*UTXO))
300 return optUtxos, optAmount, reservedAmount