estimatefee.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. // Copyright (c) 2016 The btcsuite developers
  2. // Use of this source code is governed by an ISC
  3. // license that can be found in the LICENSE file.
  4. package mempool
  5. import (
  6. "bytes"
  7. "encoding/binary"
  8. "io"
  9. "math"
  10. "math/rand"
  11. "sort"
  12. "strings"
  13. "sync"
  14. "github.com/pkt-cash/pktd/btcjson"
  15. "github.com/pkt-cash/pktd/btcutil/er"
  16. "github.com/pkt-cash/pktd/pktlog/log"
  17. "github.com/pkt-cash/pktd/btcutil"
  18. "github.com/pkt-cash/pktd/chaincfg/chainhash"
  19. "github.com/pkt-cash/pktd/chaincfg/globalcfg"
  20. "github.com/pkt-cash/pktd/mining"
  21. )
  22. // TODO incorporate Alex Morcos' modifications to Gavin's initial model
  23. // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2014-October/006824.html
  24. const (
  25. // estimateFeeDepth is the maximum number of blocks before a transaction
  26. // is confirmed that we want to track.
  27. estimateFeeDepth = 25
  28. // estimateFeeBinSize is the number of txs stored in each bin.
  29. estimateFeeBinSize = 100
  30. // estimateFeeMaxReplacements is the max number of replacements that
  31. // can be made by the txs found in a given block.
  32. estimateFeeMaxReplacements = 10
  33. // DefaultEstimateFeeMaxRollback is the default number of rollbacks
  34. // allowed by the fee estimator for orphaned blocks.
  35. DefaultEstimateFeeMaxRollback = 2
  36. // DefaultEstimateFeeMinRegisteredBlocks is the default minimum
  37. // number of blocks which must be observed by the fee estimator before
  38. // it will provide fee estimations.
  39. DefaultEstimateFeeMinRegisteredBlocks = 3
  40. bytePerKb = 1000
  41. )
  42. // EstimateFeeDatabaseKey is the key that we use to
  43. // store the fee estimator in the database.
  44. var EstimateFeeDatabaseKey = []byte("estimatefee")
  45. // SatoshiPerByte is number with units of satoshis per byte.
  46. type SatoshiPerByte float64
  47. // BtcPerKilobyte is number with units of bitcoins per kilobyte.
  48. type BtcPerKilobyte float64
  49. // ToBtcPerKb returns a float value that represents the given
  50. // SatoshiPerByte converted to satoshis per kb.
  51. func (rate SatoshiPerByte) ToBtcPerKb() BtcPerKilobyte {
  52. // If our rate is the error value, return that.
  53. if rate == SatoshiPerByte(-1.0) {
  54. return -1.0
  55. }
  56. return BtcPerKilobyte(float64(rate) * bytePerKb / float64(globalcfg.UnitsPerCoinI64()))
  57. }
  58. // NewSatoshiPerByte creates a SatoshiPerByte from an Amount and a
  59. // size in bytes.
  60. func NewSatoshiPerByte(fee btcutil.Amount, size uint32) SatoshiPerByte {
  61. return SatoshiPerByte(float64(fee) / float64(size))
  62. }
  63. // observedTransaction represents an observed transaction and some
  64. // additional data required for the fee estimation algorithm.
  65. type observedTransaction struct {
  66. // A transaction hash.
  67. hash chainhash.Hash
  68. // The fee per byte of the transaction in satoshis.
  69. feeRate SatoshiPerByte
  70. // The block height when it was observed.
  71. observed int32
  72. // The height of the block in which it was mined.
  73. // If the transaction has not yet been mined, it is zero.
  74. mined int32
  75. }
  76. func (o *observedTransaction) Serialize(w io.Writer) {
  77. binary.Write(w, binary.BigEndian, o.hash)
  78. binary.Write(w, binary.BigEndian, o.feeRate)
  79. binary.Write(w, binary.BigEndian, o.observed)
  80. binary.Write(w, binary.BigEndian, o.mined)
  81. }
  82. func deserializeObservedTransaction(r io.Reader) (*observedTransaction, er.R) {
  83. ot := observedTransaction{}
  84. // The first 32 bytes should be a hash.
  85. binary.Read(r, binary.BigEndian, &ot.hash)
  86. // The next 8 are SatoshiPerByte
  87. binary.Read(r, binary.BigEndian, &ot.feeRate)
  88. // And next there are two uint32's.
  89. binary.Read(r, binary.BigEndian, &ot.observed)
  90. binary.Read(r, binary.BigEndian, &ot.mined)
  91. return &ot, nil
  92. }
  93. // registeredBlock has the hash of a block and the list of transactions
  94. // it mined which had been previously observed by the FeeEstimator. It
  95. // is used if Rollback is called to reverse the effect of registering
  96. // a block.
  97. type registeredBlock struct {
  98. hash chainhash.Hash
  99. transactions []*observedTransaction
  100. }
  101. func (rb *registeredBlock) serialize(w io.Writer, txs map[*observedTransaction]uint32) {
  102. binary.Write(w, binary.BigEndian, rb.hash)
  103. binary.Write(w, binary.BigEndian, uint32(len(rb.transactions)))
  104. for _, o := range rb.transactions {
  105. binary.Write(w, binary.BigEndian, txs[o])
  106. }
  107. }
  108. // FeeEstimator manages the data necessary to create
  109. // fee estimations. It is safe for concurrent access.
  110. type FeeEstimator struct {
  111. maxRollback uint32
  112. binSize int32
  113. // The maximum number of replacements that can be made in a single
  114. // bin per block. Default is estimateFeeMaxReplacements
  115. maxReplacements int32
  116. // The minimum number of blocks that can be registered with the fee
  117. // estimator before it will provide answers.
  118. minRegisteredBlocks uint32
  119. // The last known height.
  120. lastKnownHeight int32
  121. // The number of blocks that have been registered.
  122. numBlocksRegistered uint32
  123. mtx sync.RWMutex
  124. observed map[chainhash.Hash]*observedTransaction
  125. bin [estimateFeeDepth][]*observedTransaction
  126. // The cached estimates.
  127. cached []SatoshiPerByte
  128. // Transactions that have been removed from the bins. This allows us to
  129. // revert in case of an orphaned block.
  130. dropped []*registeredBlock
  131. }
  132. // NewFeeEstimator creates a FeeEstimator for which at most maxRollback blocks
  133. // can be unregistered and which returns an error unless minRegisteredBlocks
  134. // have been registered with it.
  135. func NewFeeEstimator(maxRollback, minRegisteredBlocks uint32) *FeeEstimator {
  136. return &FeeEstimator{
  137. maxRollback: maxRollback,
  138. minRegisteredBlocks: minRegisteredBlocks,
  139. lastKnownHeight: mining.UnminedHeight,
  140. binSize: estimateFeeBinSize,
  141. maxReplacements: estimateFeeMaxReplacements,
  142. observed: make(map[chainhash.Hash]*observedTransaction),
  143. dropped: make([]*registeredBlock, 0, maxRollback),
  144. }
  145. }
  146. // ObserveTransaction is called when a new transaction is observed in the mempool.
  147. func (ef *FeeEstimator) ObserveTransaction(t *TxDesc) {
  148. ef.mtx.Lock()
  149. defer ef.mtx.Unlock()
  150. // If we haven't seen a block yet we don't know when this one arrived,
  151. // so we ignore it.
  152. if ef.lastKnownHeight == mining.UnminedHeight {
  153. return
  154. }
  155. hash := *t.Tx.Hash()
  156. if _, ok := ef.observed[hash]; !ok {
  157. size := uint32(GetTxVirtualSize(t.Tx))
  158. ef.observed[hash] = &observedTransaction{
  159. hash: hash,
  160. feeRate: NewSatoshiPerByte(btcutil.Amount(t.Fee), size),
  161. observed: t.Height,
  162. mined: mining.UnminedHeight,
  163. }
  164. }
  165. }
  166. // RegisterBlock informs the fee estimator of a new block to take into account.
  167. func (ef *FeeEstimator) RegisterBlock(block *btcutil.Block) er.R {
  168. ef.mtx.Lock()
  169. defer ef.mtx.Unlock()
  170. // The previous sorted list is invalid, so delete it.
  171. ef.cached = nil
  172. height := block.Height()
  173. if height != ef.lastKnownHeight+1 && ef.lastKnownHeight != mining.UnminedHeight {
  174. return er.Errorf("intermediate block not recorded; current height is %d; new height is %d",
  175. ef.lastKnownHeight, height)
  176. }
  177. // Update the last known height.
  178. ef.lastKnownHeight = height
  179. ef.numBlocksRegistered++
  180. // Randomly order txs in block.
  181. transactions := make(map[*btcutil.Tx]struct{})
  182. for _, t := range block.Transactions() {
  183. transactions[t] = struct{}{}
  184. }
  185. // Count the number of replacements we make per bin so that we don't
  186. // replace too many.
  187. var replacementCounts [estimateFeeDepth]int
  188. // Keep track of which txs were dropped in case of an orphan block.
  189. dropped := &registeredBlock{
  190. hash: *block.Hash(),
  191. transactions: make([]*observedTransaction, 0, 100),
  192. }
  193. // Go through the txs in the block.
  194. for t := range transactions {
  195. hash := *t.Hash()
  196. // Have we observed this tx in the mempool?
  197. o, ok := ef.observed[hash]
  198. if !ok {
  199. continue
  200. }
  201. // Put the observed tx in the oppropriate bin.
  202. blocksToConfirm := height - o.observed - 1
  203. // This shouldn't happen if the fee estimator works correctly,
  204. // but return an error if it does.
  205. if o.mined != mining.UnminedHeight {
  206. log.Error("Estimate fee: transaction ", hash.String(), " has already been mined")
  207. return er.New("Transaction has already been mined")
  208. }
  209. // This shouldn't happen but check just in case to avoid
  210. // an out-of-bounds array index later. This also addresses
  211. // an issue where blocksToConfirm may be negative following
  212. // a large block reorganization.
  213. if blocksToConfirm >= estimateFeeDepth || blocksToConfirm < 0 {
  214. continue
  215. }
  216. // Make sure we do not replace too many transactions per min.
  217. if replacementCounts[blocksToConfirm] == int(ef.maxReplacements) {
  218. continue
  219. }
  220. o.mined = height
  221. replacementCounts[blocksToConfirm]++
  222. bin := ef.bin[blocksToConfirm]
  223. // Remove a random element and replace it with this new tx.
  224. if len(bin) == int(ef.binSize) {
  225. // Don't drop transactions we have just added from this same block.
  226. l := int(ef.binSize) - replacementCounts[blocksToConfirm]
  227. drop := rand.Intn(l)
  228. dropped.transactions = append(dropped.transactions, bin[drop])
  229. bin[drop] = bin[l-1]
  230. bin[l-1] = o
  231. } else {
  232. bin = append(bin, o)
  233. }
  234. ef.bin[blocksToConfirm] = bin
  235. }
  236. // Go through the mempool for txs that have been in too long.
  237. for hash, o := range ef.observed {
  238. if o.mined == mining.UnminedHeight && height-o.observed >= estimateFeeDepth {
  239. delete(ef.observed, hash)
  240. }
  241. }
  242. // Add dropped list to history.
  243. if ef.maxRollback == 0 {
  244. return nil
  245. }
  246. if uint32(len(ef.dropped)) == ef.maxRollback {
  247. ef.dropped = append(ef.dropped[1:], dropped)
  248. } else {
  249. ef.dropped = append(ef.dropped, dropped)
  250. }
  251. return nil
  252. }
  253. // LastKnownHeight returns the height of the last block which was registered.
  254. func (ef *FeeEstimator) LastKnownHeight() int32 {
  255. ef.mtx.Lock()
  256. defer ef.mtx.Unlock()
  257. return ef.lastKnownHeight
  258. }
  259. // Rollback unregisters a recently registered block from the FeeEstimator.
  260. // This can be used to reverse the effect of an orphaned block on the fee
  261. // estimator. The maximum number of rollbacks allowed is given by
  262. // maxRollbacks.
  263. //
  264. // Note: not everything can be rolled back because some transactions are
  265. // deleted if they have been observed too long ago. That means the result
  266. // of Rollback won't always be exactly the same as if the last block had not
  267. // happened, but it should be close enough.
  268. func (ef *FeeEstimator) Rollback(hash *chainhash.Hash) er.R {
  269. ef.mtx.Lock()
  270. defer ef.mtx.Unlock()
  271. // Find this block in the stack of recent registered blocks.
  272. var n int
  273. for n = 1; n <= len(ef.dropped); n++ {
  274. if ef.dropped[len(ef.dropped)-n].hash.IsEqual(hash) {
  275. break
  276. }
  277. }
  278. if n > len(ef.dropped) {
  279. return er.New("no such block was recently registered")
  280. }
  281. for i := 0; i < n; i++ {
  282. ef.rollback()
  283. }
  284. return nil
  285. }
  286. // rollback rolls back the effect of the last block in the stack
  287. // of registered blocks.
  288. func (ef *FeeEstimator) rollback() {
  289. // The previous sorted list is invalid, so delete it.
  290. ef.cached = nil
  291. // pop the last list of dropped txs from the stack.
  292. last := len(ef.dropped) - 1
  293. if last == -1 {
  294. // Cannot really happen because the exported calling function
  295. // only rolls back a block already known to be in the list
  296. // of dropped transactions.
  297. return
  298. }
  299. dropped := ef.dropped[last]
  300. // where we are in each bin as we replace txs?
  301. var replacementCounters [estimateFeeDepth]int
  302. // Go through the txs in the dropped block.
  303. for _, o := range dropped.transactions {
  304. // Which bin was this tx in?
  305. blocksToConfirm := o.mined - o.observed - 1
  306. bin := ef.bin[blocksToConfirm]
  307. counter := replacementCounters[blocksToConfirm]
  308. // Continue to go through that bin where we left off.
  309. for {
  310. if counter >= len(bin) {
  311. // Panic, as we have entered an unrecoverable invalid state.
  312. panic(er.New("illegal state: cannot rollback dropped transaction"))
  313. }
  314. prev := bin[counter]
  315. if prev.mined == ef.lastKnownHeight {
  316. prev.mined = mining.UnminedHeight
  317. bin[counter] = o
  318. counter++
  319. break
  320. }
  321. counter++
  322. }
  323. replacementCounters[blocksToConfirm] = counter
  324. }
  325. // Continue going through bins to find other txs to remove
  326. // which did not replace any other when they were entered.
  327. for i, j := range replacementCounters {
  328. for {
  329. l := len(ef.bin[i])
  330. if j >= l {
  331. break
  332. }
  333. prev := ef.bin[i][j]
  334. if prev.mined == ef.lastKnownHeight {
  335. prev.mined = mining.UnminedHeight
  336. newBin := append(ef.bin[i][0:j], ef.bin[i][j+1:l]...)
  337. // TODO This line should prevent an unintentional memory
  338. // leak but it causes a panic when it is uncommented.
  339. // ef.bin[i][j] = nil
  340. ef.bin[i] = newBin
  341. continue
  342. }
  343. j++
  344. }
  345. }
  346. ef.dropped = ef.dropped[0:last]
  347. // The number of blocks the fee estimator has seen is decrimented.
  348. ef.numBlocksRegistered--
  349. ef.lastKnownHeight--
  350. }
  351. // estimateFeeSet is a set of txs that can that is sorted
  352. // by the fee per kb rate.
  353. type estimateFeeSet struct {
  354. feeRate []SatoshiPerByte
  355. bin [estimateFeeDepth]uint32
  356. }
  357. func (b *estimateFeeSet) Len() int { return len(b.feeRate) }
  358. func (b *estimateFeeSet) Less(i, j int) bool {
  359. return b.feeRate[i] > b.feeRate[j]
  360. }
  361. func (b *estimateFeeSet) Swap(i, j int) {
  362. b.feeRate[i], b.feeRate[j] = b.feeRate[j], b.feeRate[i]
  363. }
  364. // estimateFee returns the estimated fee for a transaction
  365. // to confirm in confirmations blocks from now, given
  366. // the data set we have collected.
  367. func (b *estimateFeeSet) estimateFee(confirmations int) SatoshiPerByte {
  368. if confirmations <= 0 {
  369. return SatoshiPerByte(math.Inf(1))
  370. }
  371. if confirmations > estimateFeeDepth {
  372. return 0
  373. }
  374. // We don't have any transactions!
  375. if len(b.feeRate) == 0 {
  376. return 0
  377. }
  378. var min, max int = 0, 0
  379. for i := 0; i < confirmations-1; i++ {
  380. min += int(b.bin[i])
  381. }
  382. max = min + int(b.bin[confirmations-1]) - 1
  383. if max < min {
  384. max = min
  385. }
  386. feeIndex := (min + max) / 2
  387. if feeIndex >= len(b.feeRate) {
  388. feeIndex = len(b.feeRate) - 1
  389. }
  390. return b.feeRate[feeIndex]
  391. }
  392. // newEstimateFeeSet creates a temporary data structure that
  393. // can be used to find all fee estimates.
  394. func (ef *FeeEstimator) newEstimateFeeSet() *estimateFeeSet {
  395. set := &estimateFeeSet{}
  396. capacity := 0
  397. for i, b := range ef.bin {
  398. l := len(b)
  399. set.bin[i] = uint32(l)
  400. capacity += l
  401. }
  402. set.feeRate = make([]SatoshiPerByte, capacity)
  403. i := 0
  404. for _, b := range ef.bin {
  405. for _, o := range b {
  406. set.feeRate[i] = o.feeRate
  407. i++
  408. }
  409. }
  410. sort.Sort(set)
  411. return set
  412. }
  413. // estimates returns the set of all fee estimates from 1 to estimateFeeDepth
  414. // confirmations from now.
  415. func (ef *FeeEstimator) estimates() []SatoshiPerByte {
  416. set := ef.newEstimateFeeSet()
  417. estimates := make([]SatoshiPerByte, estimateFeeDepth)
  418. for i := 0; i < estimateFeeDepth; i++ {
  419. estimates[i] = set.estimateFee(i + 1)
  420. }
  421. return estimates
  422. }
  423. // EstimateFee estimates the fee per byte to have a tx confirmed a given
  424. // number of blocks from now.
  425. func (ef *FeeEstimator) EstimateFee(numBlocks uint32) (BtcPerKilobyte, er.R) {
  426. ef.mtx.Lock()
  427. defer ef.mtx.Unlock()
  428. // If the number of registered blocks is below the minimum, return
  429. // an error.
  430. if ef.numBlocksRegistered < ef.minRegisteredBlocks {
  431. return -1, er.New("not enough blocks have been observed")
  432. }
  433. if numBlocks == 0 {
  434. return -1, er.New("cannot confirm transaction in zero blocks")
  435. }
  436. if numBlocks > estimateFeeDepth {
  437. return -1, er.Errorf(
  438. "can only estimate fees for up to %d blocks from now",
  439. estimateFeeBinSize)
  440. }
  441. // If there are no cached results, generate them.
  442. if ef.cached == nil {
  443. ef.cached = ef.estimates()
  444. }
  445. return ef.cached[int(numBlocks)-1].ToBtcPerKb(), nil
  446. }
  447. // int confTarget, FeeCalculation *feeCalc, bool conservative
  448. // This adheres to the API of estimateSmartFee but it is not actually smart.
  449. func (ef *FeeEstimator) EstimateSmartFee(numBlocks uint32, conservative bool) btcjson.EstimateSmartFeeResult {
  450. out := btcjson.EstimateSmartFeeResult{}
  451. if fpk, err := ef.EstimateFee(numBlocks); err != nil {
  452. out.Errors = append(out.Errors, err.Message())
  453. } else {
  454. btcPerKb := float64(fpk)
  455. out.FeeRate = &btcPerKb
  456. }
  457. return out
  458. }
  459. // In case the format for the serialized version of the FeeEstimator changes,
  460. // we use a version number. If the version number changes, it does not make
  461. // sense to try to upgrade a previous version to a new version. Instead, just
  462. // start fee estimation over.
  463. const estimateFeeSaveVersion = 1
  464. func deserializeRegisteredBlock(r io.Reader, txs map[uint32]*observedTransaction) (*registeredBlock, er.R) {
  465. var lenTransactions uint32
  466. rb := &registeredBlock{}
  467. binary.Read(r, binary.BigEndian, &rb.hash)
  468. binary.Read(r, binary.BigEndian, &lenTransactions)
  469. rb.transactions = make([]*observedTransaction, lenTransactions)
  470. for i := uint32(0); i < lenTransactions; i++ {
  471. var index uint32
  472. binary.Read(r, binary.BigEndian, &index)
  473. rb.transactions[i] = txs[index]
  474. }
  475. return rb, nil
  476. }
  477. // FeeEstimatorState represents a saved FeeEstimator that can be
  478. // restored with data from an earlier session of the program.
  479. type FeeEstimatorState []byte
  480. // observedTxSet is a set of txs that can that is sorted
  481. // by hash. It exists for serialization purposes so that
  482. // a serialized state always comes out the same.
  483. type observedTxSet []*observedTransaction
  484. func (q observedTxSet) Len() int { return len(q) }
  485. func (q observedTxSet) Less(i, j int) bool {
  486. return strings.Compare(q[i].hash.String(), q[j].hash.String()) < 0
  487. }
  488. func (q observedTxSet) Swap(i, j int) {
  489. q[i], q[j] = q[j], q[i]
  490. }
  491. // Save records the current state of the FeeEstimator to a []byte that
  492. // can be restored later.
  493. func (ef *FeeEstimator) Save() FeeEstimatorState {
  494. ef.mtx.Lock()
  495. defer ef.mtx.Unlock()
  496. // TODO figure out what the capacity should be.
  497. w := bytes.NewBuffer(make([]byte, 0))
  498. binary.Write(w, binary.BigEndian, uint32(estimateFeeSaveVersion))
  499. // Insert basic parameters.
  500. binary.Write(w, binary.BigEndian, &ef.maxRollback)
  501. binary.Write(w, binary.BigEndian, &ef.binSize)
  502. binary.Write(w, binary.BigEndian, &ef.maxReplacements)
  503. binary.Write(w, binary.BigEndian, &ef.minRegisteredBlocks)
  504. binary.Write(w, binary.BigEndian, &ef.lastKnownHeight)
  505. binary.Write(w, binary.BigEndian, &ef.numBlocksRegistered)
  506. // Put all the observed transactions in a sorted list.
  507. var txCount uint32
  508. ots := make([]*observedTransaction, len(ef.observed))
  509. for hash := range ef.observed {
  510. ots[txCount] = ef.observed[hash]
  511. txCount++
  512. }
  513. sort.Sort(observedTxSet(ots))
  514. txCount = 0
  515. observed := make(map[*observedTransaction]uint32)
  516. binary.Write(w, binary.BigEndian, uint32(len(ef.observed)))
  517. for _, ot := range ots {
  518. ot.Serialize(w)
  519. observed[ot] = txCount
  520. txCount++
  521. }
  522. // Save all the right bins.
  523. for _, list := range ef.bin {
  524. binary.Write(w, binary.BigEndian, uint32(len(list)))
  525. for _, o := range list {
  526. binary.Write(w, binary.BigEndian, observed[o])
  527. }
  528. }
  529. // Dropped transactions.
  530. binary.Write(w, binary.BigEndian, uint32(len(ef.dropped)))
  531. for _, registered := range ef.dropped {
  532. registered.serialize(w, observed)
  533. }
  534. // Commit the tx and return.
  535. return FeeEstimatorState(w.Bytes())
  536. }
  537. // RestoreFeeEstimator takes a FeeEstimatorState that was previously
  538. // returned by Save and restores it to a FeeEstimator
  539. func RestoreFeeEstimator(data FeeEstimatorState) (*FeeEstimator, er.R) {
  540. r := bytes.NewReader([]byte(data))
  541. // Check version
  542. var version uint32
  543. errr := binary.Read(r, binary.BigEndian, &version)
  544. if errr != nil {
  545. return nil, er.E(errr)
  546. }
  547. if version != estimateFeeSaveVersion {
  548. return nil, er.Errorf("Incorrect version: expected %d found %d", estimateFeeSaveVersion, version)
  549. }
  550. ef := &FeeEstimator{
  551. observed: make(map[chainhash.Hash]*observedTransaction),
  552. }
  553. // Read basic parameters.
  554. binary.Read(r, binary.BigEndian, &ef.maxRollback)
  555. binary.Read(r, binary.BigEndian, &ef.binSize)
  556. binary.Read(r, binary.BigEndian, &ef.maxReplacements)
  557. binary.Read(r, binary.BigEndian, &ef.minRegisteredBlocks)
  558. binary.Read(r, binary.BigEndian, &ef.lastKnownHeight)
  559. binary.Read(r, binary.BigEndian, &ef.numBlocksRegistered)
  560. // Read transactions.
  561. var numObserved uint32
  562. observed := make(map[uint32]*observedTransaction)
  563. binary.Read(r, binary.BigEndian, &numObserved)
  564. for i := uint32(0); i < numObserved; i++ {
  565. ot, err := deserializeObservedTransaction(r)
  566. if err != nil {
  567. return nil, err
  568. }
  569. observed[i] = ot
  570. ef.observed[ot.hash] = ot
  571. }
  572. // Read bins.
  573. for i := 0; i < estimateFeeDepth; i++ {
  574. var numTransactions uint32
  575. binary.Read(r, binary.BigEndian, &numTransactions)
  576. bin := make([]*observedTransaction, numTransactions)
  577. for j := uint32(0); j < numTransactions; j++ {
  578. var index uint32
  579. binary.Read(r, binary.BigEndian, &index)
  580. var exists bool
  581. bin[j], exists = observed[index]
  582. if !exists {
  583. return nil, er.Errorf("Invalid transaction reference %d", index)
  584. }
  585. }
  586. ef.bin[i] = bin
  587. }
  588. // Read dropped transactions.
  589. var numDropped uint32
  590. binary.Read(r, binary.BigEndian, &numDropped)
  591. ef.dropped = make([]*registeredBlock, numDropped)
  592. for i := uint32(0); i < numDropped; i++ {
  593. var err er.R
  594. ef.dropped[int(i)], err = deserializeRegisteredBlock(r, observed)
  595. if err != nil {
  596. return nil, err
  597. }
  598. }
  599. return ef, nil
  600. }