decred.org/dcrdex@v1.0.5/tatanka/db/bonds.go (about)

     1  // This code is available on the terms of the project LICENSE.md file,
     2  // also available online at https://blueoakcouncil.org/license/1.0.0.
     3  
     4  package db
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"time"
    10  
    11  	"decred.org/dcrdex/tatanka/tanka"
    12  )
    13  
    14  type jsonCoder struct {
    15  	thing interface{}
    16  }
    17  
    18  func newJSON(thing interface{}) *jsonCoder {
    19  	return &jsonCoder{thing}
    20  }
    21  
    22  func (p *jsonCoder) MarshalBinary() ([]byte, error) {
    23  	return json.Marshal(p.thing)
    24  }
    25  
    26  func (p *jsonCoder) UnmarshalBinary(b []byte) error {
    27  	return json.Unmarshal(b, p.thing)
    28  }
    29  
    30  func (d *DB) StoreBond(newBond *tanka.Bond) (goodBonds []*tanka.Bond, err error) {
    31  	var existingBonds []*tanka.Bond
    32  	if _, err = d.bondsDB.Get(newBond.PeerID[:], newJSON(existingBonds)); err != nil {
    33  		return nil, fmt.Errorf("error reading bonds db: %w", err)
    34  	}
    35  
    36  	for _, b := range existingBonds {
    37  		if time.Now().After(b.Expiration) {
    38  			continue
    39  		}
    40  		goodBonds = append(goodBonds, b)
    41  	}
    42  
    43  	goodBonds = append(goodBonds, newBond)
    44  	return goodBonds, d.bondsDB.Store(newBond.PeerID[:], newJSON(goodBonds))
    45  }
    46  
    47  func (d *DB) GetBonds(peerID tanka.PeerID) ([]*tanka.Bond, error) {
    48  	var existingBonds []*tanka.Bond
    49  	if _, err := d.bondsDB.Get(peerID[:], newJSON(&existingBonds)); err != nil {
    50  		return nil, fmt.Errorf("error reading bonds db: %w", err)
    51  	}
    52  
    53  	var goodBonds []*tanka.Bond
    54  	for _, b := range existingBonds {
    55  		if time.Now().After(b.Expiration) {
    56  			continue
    57  		}
    58  		goodBonds = append(goodBonds, b)
    59  	}
    60  
    61  	if len(goodBonds) != len(existingBonds) {
    62  		if err := d.bondsDB.Store(peerID[:], newJSON(goodBonds)); err != nil {
    63  			return nil, fmt.Errorf("error storing bonds after pruning: %v", err)
    64  		}
    65  	}
    66  
    67  	return goodBonds, nil
    68  }