11 log "github.com/sirupsen/logrus"
13 dbm "github.com/vapor/database/leveldb"
14 "github.com/vapor/errors"
15 "github.com/vapor/protocol/bc"
18 const desireUtxoCount = 5
20 // pre-define error types
22 ErrInsufficient = errors.New("reservation found insufficient funds")
23 ErrImmature = errors.New("reservation found immature funds")
24 ErrReserved = errors.New("reservation found outputs already reserved")
25 ErrMatchUTXO = errors.New("can't find utxo with given hash")
26 ErrReservation = errors.New("couldn't find reservation")
29 // 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, walletdb dbm.DB) *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, exp time.Time) (*reservation, error) {
116 defer uk.mtx.Unlock()
118 utxos, immatureAmount := uk.findUtxos(accountID, assetID, useUnconfirmed)
119 optUtxos, optAmount, reservedAmount := uk.optUTXOs(utxos, amount)
120 if optAmount+reservedAmount+immatureAmount < amount {
121 return nil, ErrInsufficient
124 if optAmount+reservedAmount < amount {
125 return nil, ErrImmature
128 if optAmount < amount {
129 return nil, ErrReserved
132 result := &reservation{
133 id: atomic.AddUint64(&uk.nextIndex, 1),
135 change: optAmount - amount,
139 uk.reservations[result.id] = result
140 for _, u := range optUtxos {
141 uk.reserved[u.OutputID] = result.id
146 func (uk *utxoKeeper) ReserveParticular(outHash bc.Hash, useUnconfirmed bool, exp time.Time) (*reservation, error) {
148 defer uk.mtx.Unlock()
150 if _, ok := uk.reserved[outHash]; ok {
151 return nil, ErrReserved
154 u, err := uk.findUtxo(outHash, useUnconfirmed)
159 if u.ValidHeight > uk.currentHeight() {
160 return nil, ErrImmature
163 result := &reservation{
164 id: atomic.AddUint64(&uk.nextIndex, 1),
168 uk.reservations[result.id] = result
169 uk.reserved[u.OutputID] = result.id
173 func (uk *utxoKeeper) cancel(rid uint64) {
174 res, ok := uk.reservations[rid]
179 delete(uk.reservations, rid)
180 for _, utxo := range res.utxos {
181 delete(uk.reserved, utxo.OutputID)
185 func (uk *utxoKeeper) expireWorker() {
186 ticker := time.NewTicker(1000 * time.Millisecond)
189 for now := range ticker.C {
190 uk.expireReservation(now)
194 func (uk *utxoKeeper) expireReservation(t time.Time) {
196 defer uk.mtx.Unlock()
198 for rid, res := range uk.reservations {
199 if res.expiry.Before(t) {
205 func (uk *utxoKeeper) findUtxos(accountID string, assetID *bc.AssetID, useUnconfirmed bool) ([]*UTXO, uint64) {
206 immatureAmount := uint64(0)
207 currentHeight := uk.currentHeight()
209 appendUtxo := func(u *UTXO) {
210 if u.AccountID != accountID || u.AssetID != *assetID {
213 if u.ValidHeight > currentHeight {
214 immatureAmount += u.Amount
216 utxos = append(utxos, u)
220 utxoIter := uk.db.IteratorPrefix([]byte(UTXOPreFix))
221 defer utxoIter.Release()
222 for utxoIter.Next() {
224 if err := json.Unmarshal(utxoIter.Value(), u); err != nil {
225 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("utxoKeeper findUtxos fail on unmarshal utxo")
231 return utxos, immatureAmount
234 for _, u := range uk.unconfirmed {
237 return utxos, immatureAmount
240 func (uk *utxoKeeper) findUtxo(outHash bc.Hash, useUnconfirmed bool) (*UTXO, error) {
241 if u, ok := uk.unconfirmed[outHash]; useUnconfirmed && ok {
246 if data := uk.db.Get(StandardUTXOKey(outHash)); data != nil {
247 return u, json.Unmarshal(data, u)
249 if data := uk.db.Get(ContractUTXOKey(outHash)); data != nil {
250 return u, json.Unmarshal(data, u)
252 return nil, ErrMatchUTXO
255 func (uk *utxoKeeper) optUTXOs(utxos []*UTXO, amount uint64) ([]*UTXO, uint64, uint64) {
256 //sort the utxo by amount, bigger amount in front
257 var optAmount, reservedAmount uint64
258 sort.Slice(utxos, func(i, j int) bool {
259 return utxos[i].Amount > utxos[j].Amount
262 //push all the available utxos into list
263 utxoList := list.New()
264 for _, u := range utxos {
265 if _, ok := uk.reserved[u.OutputID]; ok {
266 reservedAmount += u.Amount
272 optList := list.New()
273 for node := utxoList.Front(); node != nil; node = node.Next() {
274 //append utxo if we haven't reached the required amount
275 if optAmount < amount {
276 optList.PushBack(node.Value)
277 optAmount += node.Value.(*UTXO).Amount
281 largestNode := optList.Front()
282 replaceList := list.New()
283 replaceAmount := optAmount - largestNode.Value.(*UTXO).Amount
285 for ; node != nil && replaceList.Len() <= desireUtxoCount-optList.Len(); node = node.Next() {
286 replaceList.PushBack(node.Value)
287 if replaceAmount += node.Value.(*UTXO).Amount; replaceAmount >= amount {
288 optList.Remove(largestNode)
289 optList.PushBackList(replaceList)
290 optAmount = replaceAmount
295 //largestNode remaining the same means that there is nothing to be replaced
296 if largestNode == optList.Front() {
301 optUtxos := []*UTXO{}
302 for e := optList.Front(); e != nil; e = e.Next() {
303 optUtxos = append(optUtxos, e.Value.(*UTXO))
305 return optUtxos, optAmount, reservedAmount