12 log "github.com/sirupsen/logrus"
14 dbm "github.com/vapor/database/leveldb"
15 "github.com/vapor/errors"
16 "github.com/vapor/protocol/bc"
19 const desireUtxoCount = 5
21 // pre-define error types
23 ErrInsufficient = errors.New("reservation found insufficient funds")
24 ErrImmature = errors.New("reservation found immature funds")
25 ErrReserved = errors.New("reservation found outputs already reserved")
26 ErrMatchUTXO = errors.New("can't find utxo with given hash")
27 ErrReservation = errors.New("couldn't find reservation")
30 // UTXO describes an individual account utxo.
41 ControlProgramIndex uint64
46 // reservation describes a reservation of a set of UTXOs
47 type reservation struct {
54 type utxoKeeper struct {
55 // `sync/atomic` expects the first word in an allocated struct to be 64-bit
56 // aligned on both ARM and x86-32. See https://goo.gl/zW7dgq for more details.
60 currentHeight func() uint64
62 unconfirmed map[bc.Hash]*UTXO
63 reserved map[bc.Hash]uint64
64 reservations map[uint64]*reservation
67 func newUtxoKeeper(f func() uint64, walletdb dbm.DB) *utxoKeeper {
71 unconfirmed: make(map[bc.Hash]*UTXO),
72 reserved: make(map[bc.Hash]uint64),
73 reservations: make(map[uint64]*reservation),
79 func (uk *utxoKeeper) AddUnconfirmedUtxo(utxos []*UTXO) {
83 for _, utxo := range utxos {
84 uk.unconfirmed[utxo.OutputID] = utxo
88 // Cancel canceling the reservation with the provided ID.
89 func (uk *utxoKeeper) Cancel(rid uint64) {
95 // ListUnconfirmed return all the unconfirmed utxos
96 func (uk *utxoKeeper) ListUnconfirmed() []*UTXO {
101 for _, utxo := range uk.unconfirmed {
102 utxos = append(utxos, utxo)
107 func (uk *utxoKeeper) RemoveUnconfirmedUtxo(hashes []*bc.Hash) {
109 defer uk.mtx.Unlock()
111 for _, hash := range hashes {
112 delete(uk.unconfirmed, *hash)
116 func (uk *utxoKeeper) Reserve(accountID string, assetID *bc.AssetID, amount uint64, useUnconfirmed bool, vote []byte, exp time.Time) (*reservation, error) {
118 defer uk.mtx.Unlock()
120 utxos, immatureAmount := uk.findUtxos(accountID, assetID, useUnconfirmed, vote)
121 optUtxos, optAmount, reservedAmount := uk.optUTXOs(utxos, amount)
122 if optAmount+reservedAmount+immatureAmount < amount {
123 return nil, ErrInsufficient
126 if optAmount+reservedAmount < amount {
127 return nil, ErrImmature
130 if optAmount < amount {
131 return nil, ErrReserved
134 result := &reservation{
135 id: atomic.AddUint64(&uk.nextIndex, 1),
137 change: optAmount - amount,
141 uk.reservations[result.id] = result
142 for _, u := range optUtxos {
143 uk.reserved[u.OutputID] = result.id
148 func (uk *utxoKeeper) ReserveParticular(outHash bc.Hash, useUnconfirmed bool, exp time.Time) (*reservation, error) {
150 defer uk.mtx.Unlock()
152 if _, ok := uk.reserved[outHash]; ok {
153 return nil, ErrReserved
156 u, err := uk.findUtxo(outHash, useUnconfirmed)
161 if u.ValidHeight > uk.currentHeight() {
162 return nil, ErrImmature
165 result := &reservation{
166 id: atomic.AddUint64(&uk.nextIndex, 1),
170 uk.reservations[result.id] = result
171 uk.reserved[u.OutputID] = result.id
175 func (uk *utxoKeeper) cancel(rid uint64) {
176 res, ok := uk.reservations[rid]
181 delete(uk.reservations, rid)
182 for _, utxo := range res.utxos {
183 delete(uk.reserved, utxo.OutputID)
187 func (uk *utxoKeeper) expireWorker() {
188 ticker := time.NewTicker(1000 * time.Millisecond)
191 for now := range ticker.C {
192 uk.expireReservation(now)
196 func (uk *utxoKeeper) expireReservation(t time.Time) {
198 defer uk.mtx.Unlock()
200 for rid, res := range uk.reservations {
201 if res.expiry.Before(t) {
207 func (uk *utxoKeeper) findUtxos(accountID string, assetID *bc.AssetID, useUnconfirmed bool, vote []byte) ([]*UTXO, uint64) {
208 immatureAmount := uint64(0)
209 currentHeight := uk.currentHeight()
211 appendUtxo := func(u *UTXO) {
212 if u.AccountID != accountID || u.AssetID != *assetID || !bytes.Equal(u.Vote, vote) {
215 if u.ValidHeight > currentHeight {
216 immatureAmount += u.Amount
218 utxos = append(utxos, u)
222 utxoIter := uk.db.IteratorPrefix([]byte(UTXOPreFix))
223 defer utxoIter.Release()
224 for utxoIter.Next() {
226 if err := json.Unmarshal(utxoIter.Value(), u); err != nil {
227 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("utxoKeeper findUtxos fail on unmarshal utxo")
233 return utxos, immatureAmount
236 for _, u := range uk.unconfirmed {
239 return utxos, immatureAmount
242 func (uk *utxoKeeper) findUtxo(outHash bc.Hash, useUnconfirmed bool) (*UTXO, error) {
243 if u, ok := uk.unconfirmed[outHash]; useUnconfirmed && ok {
248 if data := uk.db.Get(StandardUTXOKey(outHash)); data != nil {
249 return u, json.Unmarshal(data, u)
251 if data := uk.db.Get(ContractUTXOKey(outHash)); data != nil {
252 return u, json.Unmarshal(data, u)
254 return nil, ErrMatchUTXO
257 func (uk *utxoKeeper) optUTXOs(utxos []*UTXO, amount uint64) ([]*UTXO, uint64, uint64) {
258 //sort the utxo by amount, bigger amount in front
259 var optAmount, reservedAmount uint64
260 sort.Slice(utxos, func(i, j int) bool {
261 return utxos[i].Amount > utxos[j].Amount
264 //push all the available utxos into list
265 utxoList := list.New()
266 for _, u := range utxos {
267 if _, ok := uk.reserved[u.OutputID]; ok {
268 reservedAmount += u.Amount
274 optList := list.New()
275 for node := utxoList.Front(); node != nil; node = node.Next() {
276 //append utxo if we haven't reached the required amount
277 if optAmount < amount {
278 optList.PushBack(node.Value)
279 optAmount += node.Value.(*UTXO).Amount
283 largestNode := optList.Front()
284 replaceList := list.New()
285 replaceAmount := optAmount - largestNode.Value.(*UTXO).Amount
287 for ; node != nil && replaceList.Len() <= desireUtxoCount-optList.Len(); node = node.Next() {
288 replaceList.PushBack(node.Value)
289 if replaceAmount += node.Value.(*UTXO).Amount; replaceAmount >= amount {
290 optList.Remove(largestNode)
291 optList.PushBackList(replaceList)
292 optAmount = replaceAmount
297 //largestNode remaining the same means that there is nothing to be replaced
298 if largestNode == optList.Front() {
303 optUtxos := []*UTXO{}
304 for e := optList.Front(); e != nil; e = e.Next() {
305 optUtxos = append(optUtxos, e.Value.(*UTXO))
307 return optUtxos, optAmount, reservedAmount