payments.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  1. package channeldb
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "sort"
  9. "time"
  10. "github.com/btcsuite/btcd/btcec/v2"
  11. "github.com/btcsuite/btcd/wire"
  12. "github.com/lightningnetwork/lnd/kvdb"
  13. "github.com/lightningnetwork/lnd/lntypes"
  14. "github.com/lightningnetwork/lnd/lnwire"
  15. "github.com/lightningnetwork/lnd/record"
  16. "github.com/lightningnetwork/lnd/routing/route"
  17. "github.com/lightningnetwork/lnd/tlv"
  18. )
  19. var (
  20. // paymentsRootBucket is the name of the top-level bucket within the
  21. // database that stores all data related to payments. Within this
  22. // bucket, each payment hash its own sub-bucket keyed by its payment
  23. // hash.
  24. //
  25. // Bucket hierarchy:
  26. //
  27. // root-bucket
  28. // |
  29. // |-- <paymenthash>
  30. // | |--sequence-key: <sequence number>
  31. // | |--creation-info-key: <creation info>
  32. // | |--fail-info-key: <(optional) fail info>
  33. // | |
  34. // | |--payment-htlcs-bucket (shard-bucket)
  35. // | | |
  36. // | | |-- ai<htlc attempt ID>: <htlc attempt info>
  37. // | | |-- si<htlc attempt ID>: <(optional) settle info>
  38. // | | |-- fi<htlc attempt ID>: <(optional) fail info>
  39. // | | |
  40. // | | ...
  41. // | |
  42. // | |
  43. // | |--duplicate-bucket (only for old, completed payments)
  44. // | |
  45. // | |-- <seq-num>
  46. // | | |--sequence-key: <sequence number>
  47. // | | |--creation-info-key: <creation info>
  48. // | | |--ai: <attempt info>
  49. // | | |--si: <settle info>
  50. // | | |--fi: <fail info>
  51. // | |
  52. // | |-- <seq-num>
  53. // | | |
  54. // | ... ...
  55. // |
  56. // |-- <paymenthash>
  57. // | |
  58. // | ...
  59. // ...
  60. //
  61. paymentsRootBucket = []byte("payments-root-bucket")
  62. // paymentSequenceKey is a key used in the payment's sub-bucket to
  63. // store the sequence number of the payment.
  64. paymentSequenceKey = []byte("payment-sequence-key")
  65. // paymentCreationInfoKey is a key used in the payment's sub-bucket to
  66. // store the creation info of the payment.
  67. paymentCreationInfoKey = []byte("payment-creation-info")
  68. // paymentHtlcsBucket is a bucket where we'll store the information
  69. // about the HTLCs that were attempted for a payment.
  70. paymentHtlcsBucket = []byte("payment-htlcs-bucket")
  71. // htlcAttemptInfoKey is the key used as the prefix of an HTLC attempt
  72. // to store the info about the attempt that was done for the HTLC in
  73. // question. The HTLC attempt ID is concatenated at the end.
  74. htlcAttemptInfoKey = []byte("ai")
  75. // htlcSettleInfoKey is the key used as the prefix of an HTLC attempt
  76. // settle info, if any. The HTLC attempt ID is concatenated at the end.
  77. htlcSettleInfoKey = []byte("si")
  78. // htlcFailInfoKey is the key used as the prefix of an HTLC attempt
  79. // failure information, if any.The HTLC attempt ID is concatenated at
  80. // the end.
  81. htlcFailInfoKey = []byte("fi")
  82. // paymentFailInfoKey is a key used in the payment's sub-bucket to
  83. // store information about the reason a payment failed.
  84. paymentFailInfoKey = []byte("payment-fail-info")
  85. // paymentsIndexBucket is the name of the top-level bucket within the
  86. // database that stores an index of payment sequence numbers to its
  87. // payment hash.
  88. // payments-sequence-index-bucket
  89. // |--<sequence-number>: <payment hash>
  90. // |--...
  91. // |--<sequence-number>: <payment hash>
  92. paymentsIndexBucket = []byte("payments-index-bucket")
  93. )
  94. var (
  95. // ErrNoSequenceNumber is returned if we lookup a payment which does
  96. // not have a sequence number.
  97. ErrNoSequenceNumber = errors.New("sequence number not found")
  98. // ErrDuplicateNotFound is returned when we lookup a payment by its
  99. // index and cannot find a payment with a matching sequence number.
  100. ErrDuplicateNotFound = errors.New("duplicate payment not found")
  101. // ErrNoDuplicateBucket is returned when we expect to find duplicates
  102. // when looking up a payment from its index, but the payment does not
  103. // have any.
  104. ErrNoDuplicateBucket = errors.New("expected duplicate bucket")
  105. // ErrNoDuplicateNestedBucket is returned if we do not find duplicate
  106. // payments in their own sub-bucket.
  107. ErrNoDuplicateNestedBucket = errors.New("nested duplicate bucket not " +
  108. "found")
  109. )
  110. // FailureReason encodes the reason a payment ultimately failed.
  111. type FailureReason byte
  112. const (
  113. // FailureReasonTimeout indicates that the payment did timeout before a
  114. // successful payment attempt was made.
  115. FailureReasonTimeout FailureReason = 0
  116. // FailureReasonNoRoute indicates no successful route to the
  117. // destination was found during path finding.
  118. FailureReasonNoRoute FailureReason = 1
  119. // FailureReasonError indicates that an unexpected error happened during
  120. // payment.
  121. FailureReasonError FailureReason = 2
  122. // FailureReasonPaymentDetails indicates that either the hash is unknown
  123. // or the final cltv delta or amount is incorrect.
  124. FailureReasonPaymentDetails FailureReason = 3
  125. // FailureReasonInsufficientBalance indicates that we didn't have enough
  126. // balance to complete the payment.
  127. FailureReasonInsufficientBalance FailureReason = 4
  128. // TODO(halseth): cancel state.
  129. // TODO(joostjager): Add failure reasons for:
  130. // LocalLiquidityInsufficient, RemoteCapacityInsufficient.
  131. )
  132. // Error returns a human readable error string for the FailureReason.
  133. func (r FailureReason) Error() string {
  134. return r.String()
  135. }
  136. // String returns a human readable FailureReason.
  137. func (r FailureReason) String() string {
  138. switch r {
  139. case FailureReasonTimeout:
  140. return "timeout"
  141. case FailureReasonNoRoute:
  142. return "no_route"
  143. case FailureReasonError:
  144. return "error"
  145. case FailureReasonPaymentDetails:
  146. return "incorrect_payment_details"
  147. case FailureReasonInsufficientBalance:
  148. return "insufficient_balance"
  149. }
  150. return "unknown"
  151. }
  152. // PaymentCreationInfo is the information necessary to have ready when
  153. // initiating a payment, moving it into state InFlight.
  154. type PaymentCreationInfo struct {
  155. // PaymentIdentifier is the hash this payment is paying to in case of
  156. // non-AMP payments, and the SetID for AMP payments.
  157. PaymentIdentifier lntypes.Hash
  158. // Value is the amount we are paying.
  159. Value lnwire.MilliSatoshi
  160. // CreationTime is the time when this payment was initiated.
  161. CreationTime time.Time
  162. // PaymentRequest is the full payment request, if any.
  163. PaymentRequest []byte
  164. }
  165. // htlcBucketKey creates a composite key from prefix and id where the result is
  166. // simply the two concatenated.
  167. func htlcBucketKey(prefix, id []byte) []byte {
  168. key := make([]byte, len(prefix)+len(id))
  169. copy(key, prefix)
  170. copy(key[len(prefix):], id)
  171. return key
  172. }
  173. // FetchPayments returns all sent payments found in the DB.
  174. //
  175. // nolint: dupl
  176. func (d *DB) FetchPayments() ([]*MPPayment, error) {
  177. var payments []*MPPayment
  178. err := kvdb.View(d, func(tx kvdb.RTx) error {
  179. paymentsBucket := tx.ReadBucket(paymentsRootBucket)
  180. if paymentsBucket == nil {
  181. return nil
  182. }
  183. return paymentsBucket.ForEach(func(k, v []byte) error {
  184. bucket := paymentsBucket.NestedReadBucket(k)
  185. if bucket == nil {
  186. // We only expect sub-buckets to be found in
  187. // this top-level bucket.
  188. return fmt.Errorf("non bucket element in " +
  189. "payments bucket")
  190. }
  191. p, err := fetchPayment(bucket)
  192. if err != nil {
  193. return err
  194. }
  195. payments = append(payments, p)
  196. // For older versions of lnd, duplicate payments to a
  197. // payment has was possible. These will be found in a
  198. // sub-bucket indexed by their sequence number if
  199. // available.
  200. duplicatePayments, err := fetchDuplicatePayments(bucket)
  201. if err != nil {
  202. return err
  203. }
  204. payments = append(payments, duplicatePayments...)
  205. return nil
  206. })
  207. }, func() {
  208. payments = nil
  209. })
  210. if err != nil {
  211. return nil, err
  212. }
  213. // Before returning, sort the payments by their sequence number.
  214. sort.Slice(payments, func(i, j int) bool {
  215. return payments[i].SequenceNum < payments[j].SequenceNum
  216. })
  217. return payments, nil
  218. }
  219. func fetchCreationInfo(bucket kvdb.RBucket) (*PaymentCreationInfo, error) {
  220. b := bucket.Get(paymentCreationInfoKey)
  221. if b == nil {
  222. return nil, fmt.Errorf("creation info not found")
  223. }
  224. r := bytes.NewReader(b)
  225. return deserializePaymentCreationInfo(r)
  226. }
  227. func fetchPayment(bucket kvdb.RBucket) (*MPPayment, error) {
  228. seqBytes := bucket.Get(paymentSequenceKey)
  229. if seqBytes == nil {
  230. return nil, fmt.Errorf("sequence number not found")
  231. }
  232. sequenceNum := binary.BigEndian.Uint64(seqBytes)
  233. // Get the PaymentCreationInfo.
  234. creationInfo, err := fetchCreationInfo(bucket)
  235. if err != nil {
  236. return nil, err
  237. }
  238. var htlcs []HTLCAttempt
  239. htlcsBucket := bucket.NestedReadBucket(paymentHtlcsBucket)
  240. if htlcsBucket != nil {
  241. // Get the payment attempts. This can be empty.
  242. htlcs, err = fetchHtlcAttempts(htlcsBucket)
  243. if err != nil {
  244. return nil, err
  245. }
  246. }
  247. // Get failure reason if available.
  248. var failureReason *FailureReason
  249. b := bucket.Get(paymentFailInfoKey)
  250. if b != nil {
  251. reason := FailureReason(b[0])
  252. failureReason = &reason
  253. }
  254. // Create a new payment.
  255. payment := &MPPayment{
  256. SequenceNum: sequenceNum,
  257. Info: creationInfo,
  258. HTLCs: htlcs,
  259. FailureReason: failureReason,
  260. }
  261. // Set its state and status.
  262. if err := payment.setState(); err != nil {
  263. return nil, err
  264. }
  265. return payment, nil
  266. }
  267. // fetchHtlcAttempts retrieves all htlc attempts made for the payment found in
  268. // the given bucket.
  269. func fetchHtlcAttempts(bucket kvdb.RBucket) ([]HTLCAttempt, error) {
  270. htlcsMap := make(map[uint64]*HTLCAttempt)
  271. attemptInfoCount := 0
  272. err := bucket.ForEach(func(k, v []byte) error {
  273. aid := byteOrder.Uint64(k[len(k)-8:])
  274. if _, ok := htlcsMap[aid]; !ok {
  275. htlcsMap[aid] = &HTLCAttempt{}
  276. }
  277. var err error
  278. switch {
  279. case bytes.HasPrefix(k, htlcAttemptInfoKey):
  280. attemptInfo, err := readHtlcAttemptInfo(v)
  281. if err != nil {
  282. return err
  283. }
  284. attemptInfo.AttemptID = aid
  285. htlcsMap[aid].HTLCAttemptInfo = *attemptInfo
  286. attemptInfoCount++
  287. case bytes.HasPrefix(k, htlcSettleInfoKey):
  288. htlcsMap[aid].Settle, err = readHtlcSettleInfo(v)
  289. if err != nil {
  290. return err
  291. }
  292. case bytes.HasPrefix(k, htlcFailInfoKey):
  293. htlcsMap[aid].Failure, err = readHtlcFailInfo(v)
  294. if err != nil {
  295. return err
  296. }
  297. default:
  298. return fmt.Errorf("unknown htlc attempt key")
  299. }
  300. return nil
  301. })
  302. if err != nil {
  303. return nil, err
  304. }
  305. // Sanity check that all htlcs have an attempt info.
  306. if attemptInfoCount != len(htlcsMap) {
  307. return nil, errNoAttemptInfo
  308. }
  309. keys := make([]uint64, len(htlcsMap))
  310. i := 0
  311. for k := range htlcsMap {
  312. keys[i] = k
  313. i++
  314. }
  315. // Sort HTLC attempts by their attempt ID. This is needed because in the
  316. // DB we store the attempts with keys prefixed by their status which
  317. // changes order (groups them together by status).
  318. sort.Slice(keys, func(i, j int) bool {
  319. return keys[i] < keys[j]
  320. })
  321. htlcs := make([]HTLCAttempt, len(htlcsMap))
  322. for i, key := range keys {
  323. htlcs[i] = *htlcsMap[key]
  324. }
  325. return htlcs, nil
  326. }
  327. // readHtlcAttemptInfo reads the payment attempt info for this htlc.
  328. func readHtlcAttemptInfo(b []byte) (*HTLCAttemptInfo, error) {
  329. r := bytes.NewReader(b)
  330. return deserializeHTLCAttemptInfo(r)
  331. }
  332. // readHtlcSettleInfo reads the settle info for the htlc. If the htlc isn't
  333. // settled, nil is returned.
  334. func readHtlcSettleInfo(b []byte) (*HTLCSettleInfo, error) {
  335. r := bytes.NewReader(b)
  336. return deserializeHTLCSettleInfo(r)
  337. }
  338. // readHtlcFailInfo reads the failure info for the htlc. If the htlc hasn't
  339. // failed, nil is returned.
  340. func readHtlcFailInfo(b []byte) (*HTLCFailInfo, error) {
  341. r := bytes.NewReader(b)
  342. return deserializeHTLCFailInfo(r)
  343. }
  344. // fetchFailedHtlcKeys retrieves the bucket keys of all failed HTLCs of a
  345. // payment bucket.
  346. func fetchFailedHtlcKeys(bucket kvdb.RBucket) ([][]byte, error) {
  347. htlcsBucket := bucket.NestedReadBucket(paymentHtlcsBucket)
  348. var htlcs []HTLCAttempt
  349. var err error
  350. if htlcsBucket != nil {
  351. htlcs, err = fetchHtlcAttempts(htlcsBucket)
  352. if err != nil {
  353. return nil, err
  354. }
  355. }
  356. // Now iterate though them and save the bucket keys for the failed
  357. // HTLCs.
  358. var htlcKeys [][]byte
  359. for _, h := range htlcs {
  360. if h.Failure == nil {
  361. continue
  362. }
  363. htlcKeyBytes := make([]byte, 8)
  364. binary.BigEndian.PutUint64(htlcKeyBytes, h.AttemptID)
  365. htlcKeys = append(htlcKeys, htlcKeyBytes)
  366. }
  367. return htlcKeys, nil
  368. }
  369. // PaymentsQuery represents a query to the payments database starting or ending
  370. // at a certain offset index. The number of retrieved records can be limited.
  371. type PaymentsQuery struct {
  372. // IndexOffset determines the starting point of the payments query and
  373. // is always exclusive. In normal order, the query starts at the next
  374. // higher (available) index compared to IndexOffset. In reversed order,
  375. // the query ends at the next lower (available) index compared to the
  376. // IndexOffset. In the case of a zero index_offset, the query will start
  377. // with the oldest payment when paginating forwards, or will end with
  378. // the most recent payment when paginating backwards.
  379. IndexOffset uint64
  380. // MaxPayments is the maximal number of payments returned in the
  381. // payments query.
  382. MaxPayments uint64
  383. // Reversed gives a meaning to the IndexOffset. If reversed is set to
  384. // true, the query will fetch payments with indices lower than the
  385. // IndexOffset, otherwise, it will return payments with indices greater
  386. // than the IndexOffset.
  387. Reversed bool
  388. // If IncludeIncomplete is true, then return payments that have not yet
  389. // fully completed. This means that pending payments, as well as failed
  390. // payments will show up if this field is set to true.
  391. IncludeIncomplete bool
  392. // CountTotal indicates that all payments currently present in the
  393. // payment index (complete and incomplete) should be counted.
  394. CountTotal bool
  395. // CreationDateStart, expressed in Unix seconds, if set, filters out
  396. // all payments with a creation date greater than or equal to it.
  397. CreationDateStart int64
  398. // CreationDateEnd, expressed in Unix seconds, if set, filters out all
  399. // payments with a creation date less than or equal to it.
  400. CreationDateEnd int64
  401. }
  402. // PaymentsResponse contains the result of a query to the payments database.
  403. // It includes the set of payments that match the query and integers which
  404. // represent the index of the first and last item returned in the series of
  405. // payments. These integers allow callers to resume their query in the event
  406. // that the query's response exceeds the max number of returnable events.
  407. type PaymentsResponse struct {
  408. // Payments is the set of payments returned from the database for the
  409. // PaymentsQuery.
  410. Payments []*MPPayment
  411. // FirstIndexOffset is the index of the first element in the set of
  412. // returned MPPayments. Callers can use this to resume their query
  413. // in the event that the slice has too many events to fit into a single
  414. // response. The offset can be used to continue reverse pagination.
  415. FirstIndexOffset uint64
  416. // LastIndexOffset is the index of the last element in the set of
  417. // returned MPPayments. Callers can use this to resume their query
  418. // in the event that the slice has too many events to fit into a single
  419. // response. The offset can be used to continue forward pagination.
  420. LastIndexOffset uint64
  421. // TotalCount represents the total number of payments that are currently
  422. // stored in the payment database. This will only be set if the
  423. // CountTotal field in the query was set to true.
  424. TotalCount uint64
  425. }
  426. // QueryPayments is a query to the payments database which is restricted
  427. // to a subset of payments by the payments query, containing an offset
  428. // index and a maximum number of returned payments.
  429. func (d *DB) QueryPayments(query PaymentsQuery) (PaymentsResponse, error) {
  430. var resp PaymentsResponse
  431. if err := kvdb.View(d, func(tx kvdb.RTx) error {
  432. // Get the root payments bucket.
  433. paymentsBucket := tx.ReadBucket(paymentsRootBucket)
  434. if paymentsBucket == nil {
  435. return nil
  436. }
  437. // Get the index bucket which maps sequence number -> payment
  438. // hash and duplicate bool. If we have a payments bucket, we
  439. // should have an indexes bucket as well.
  440. indexes := tx.ReadBucket(paymentsIndexBucket)
  441. if indexes == nil {
  442. return fmt.Errorf("index bucket does not exist")
  443. }
  444. // accumulatePayments gets payments with the sequence number
  445. // and hash provided and adds them to our list of payments if
  446. // they meet the criteria of our query. It returns the number
  447. // of payments that were added.
  448. accumulatePayments := func(sequenceKey, hash []byte) (bool,
  449. error) {
  450. r := bytes.NewReader(hash)
  451. paymentHash, err := deserializePaymentIndex(r)
  452. if err != nil {
  453. return false, err
  454. }
  455. payment, err := fetchPaymentWithSequenceNumber(
  456. tx, paymentHash, sequenceKey,
  457. )
  458. if err != nil {
  459. return false, err
  460. }
  461. // To keep compatibility with the old API, we only
  462. // return non-succeeded payments if requested.
  463. if payment.Status != StatusSucceeded &&
  464. !query.IncludeIncomplete {
  465. return false, err
  466. }
  467. // Get the creation time in Unix seconds, this always
  468. // rounds down the nanoseconds to full seconds.
  469. createTime := payment.Info.CreationTime.Unix()
  470. // Skip any payments that were created before the
  471. // specified time.
  472. if createTime < query.CreationDateStart {
  473. return false, nil
  474. }
  475. // Skip any payments that were created after the
  476. // specified time.
  477. if query.CreationDateEnd != 0 &&
  478. createTime > query.CreationDateEnd {
  479. return false, nil
  480. }
  481. // At this point, we've exhausted the offset, so we'll
  482. // begin collecting invoices found within the range.
  483. resp.Payments = append(resp.Payments, payment)
  484. return true, nil
  485. }
  486. // Create a paginator which reads from our sequence index bucket
  487. // with the parameters provided by the payments query.
  488. paginator := newPaginator(
  489. indexes.ReadCursor(), query.Reversed, query.IndexOffset,
  490. query.MaxPayments,
  491. )
  492. // Run a paginated query, adding payments to our response.
  493. if err := paginator.query(accumulatePayments); err != nil {
  494. return err
  495. }
  496. // Counting the total number of payments is expensive, since we
  497. // literally have to traverse the cursor linearly, which can
  498. // take quite a while. So it's an optional query parameter.
  499. if query.CountTotal {
  500. var (
  501. totalPayments uint64
  502. err error
  503. )
  504. countFn := func(_, _ []byte) error {
  505. totalPayments++
  506. return nil
  507. }
  508. // In non-boltdb database backends, there's a faster
  509. // ForAll query that allows for batch fetching items.
  510. if fastBucket, ok := indexes.(kvdb.ExtendedRBucket); ok {
  511. err = fastBucket.ForAll(countFn)
  512. } else {
  513. err = indexes.ForEach(countFn)
  514. }
  515. if err != nil {
  516. return fmt.Errorf("error counting payments: %w",
  517. err)
  518. }
  519. resp.TotalCount = totalPayments
  520. }
  521. return nil
  522. }, func() {
  523. resp = PaymentsResponse{}
  524. }); err != nil {
  525. return resp, err
  526. }
  527. // Need to swap the payments slice order if reversed order.
  528. if query.Reversed {
  529. for l, r := 0, len(resp.Payments)-1; l < r; l, r = l+1, r-1 {
  530. resp.Payments[l], resp.Payments[r] =
  531. resp.Payments[r], resp.Payments[l]
  532. }
  533. }
  534. // Set the first and last index of the returned payments so that the
  535. // caller can resume from this point later on.
  536. if len(resp.Payments) > 0 {
  537. resp.FirstIndexOffset = resp.Payments[0].SequenceNum
  538. resp.LastIndexOffset =
  539. resp.Payments[len(resp.Payments)-1].SequenceNum
  540. }
  541. return resp, nil
  542. }
  543. // fetchPaymentWithSequenceNumber get the payment which matches the payment hash
  544. // *and* sequence number provided from the database. This is required because
  545. // we previously had more than one payment per hash, so we have multiple indexes
  546. // pointing to a single payment; we want to retrieve the correct one.
  547. func fetchPaymentWithSequenceNumber(tx kvdb.RTx, paymentHash lntypes.Hash,
  548. sequenceNumber []byte) (*MPPayment, error) {
  549. // We can now lookup the payment keyed by its hash in
  550. // the payments root bucket.
  551. bucket, err := fetchPaymentBucket(tx, paymentHash)
  552. if err != nil {
  553. return nil, err
  554. }
  555. // A single payment hash can have multiple payments associated with it.
  556. // We lookup our sequence number first, to determine whether this is
  557. // the payment we are actually looking for.
  558. seqBytes := bucket.Get(paymentSequenceKey)
  559. if seqBytes == nil {
  560. return nil, ErrNoSequenceNumber
  561. }
  562. // If this top level payment has the sequence number we are looking for,
  563. // return it.
  564. if bytes.Equal(seqBytes, sequenceNumber) {
  565. return fetchPayment(bucket)
  566. }
  567. // If we were not looking for the top level payment, we are looking for
  568. // one of our duplicate payments. We need to iterate through the seq
  569. // numbers in this bucket to find the correct payments. If we do not
  570. // find a duplicate payments bucket here, something is wrong.
  571. dup := bucket.NestedReadBucket(duplicatePaymentsBucket)
  572. if dup == nil {
  573. return nil, ErrNoDuplicateBucket
  574. }
  575. var duplicatePayment *MPPayment
  576. err = dup.ForEach(func(k, v []byte) error {
  577. subBucket := dup.NestedReadBucket(k)
  578. if subBucket == nil {
  579. // We one bucket for each duplicate to be found.
  580. return ErrNoDuplicateNestedBucket
  581. }
  582. seqBytes := subBucket.Get(duplicatePaymentSequenceKey)
  583. if seqBytes == nil {
  584. return err
  585. }
  586. // If this duplicate payment is not the sequence number we are
  587. // looking for, we can continue.
  588. if !bytes.Equal(seqBytes, sequenceNumber) {
  589. return nil
  590. }
  591. duplicatePayment, err = fetchDuplicatePayment(subBucket)
  592. if err != nil {
  593. return err
  594. }
  595. return nil
  596. })
  597. if err != nil {
  598. return nil, err
  599. }
  600. // If none of the duplicate payments matched our sequence number, we
  601. // failed to find the payment with this sequence number; something is
  602. // wrong.
  603. if duplicatePayment == nil {
  604. return nil, ErrDuplicateNotFound
  605. }
  606. return duplicatePayment, nil
  607. }
  608. // DeletePayment deletes a payment from the DB given its payment hash. If
  609. // failedHtlcsOnly is set, only failed HTLC attempts of the payment will be
  610. // deleted.
  611. func (d *DB) DeletePayment(paymentHash lntypes.Hash,
  612. failedHtlcsOnly bool) error {
  613. return kvdb.Update(d, func(tx kvdb.RwTx) error {
  614. payments := tx.ReadWriteBucket(paymentsRootBucket)
  615. if payments == nil {
  616. return nil
  617. }
  618. bucket := payments.NestedReadWriteBucket(paymentHash[:])
  619. if bucket == nil {
  620. return fmt.Errorf("non bucket element in payments " +
  621. "bucket")
  622. }
  623. // If the status is InFlight, we cannot safely delete
  624. // the payment information, so we return early.
  625. paymentStatus, err := fetchPaymentStatus(bucket)
  626. if err != nil {
  627. return err
  628. }
  629. // If the payment has inflight HTLCs, we cannot safely delete
  630. // the payment information, so we return an error.
  631. if err := paymentStatus.removable(); err != nil {
  632. return fmt.Errorf("payment '%v' has inflight HTLCs"+
  633. "and therefore cannot be deleted: %w",
  634. paymentHash.String(), err)
  635. }
  636. // Delete the failed HTLC attempts we found.
  637. if failedHtlcsOnly {
  638. toDelete, err := fetchFailedHtlcKeys(bucket)
  639. if err != nil {
  640. return err
  641. }
  642. htlcsBucket := bucket.NestedReadWriteBucket(
  643. paymentHtlcsBucket,
  644. )
  645. for _, htlcID := range toDelete {
  646. err = htlcsBucket.Delete(
  647. htlcBucketKey(htlcAttemptInfoKey, htlcID),
  648. )
  649. if err != nil {
  650. return err
  651. }
  652. err = htlcsBucket.Delete(
  653. htlcBucketKey(htlcFailInfoKey, htlcID),
  654. )
  655. if err != nil {
  656. return err
  657. }
  658. err = htlcsBucket.Delete(
  659. htlcBucketKey(htlcSettleInfoKey, htlcID),
  660. )
  661. if err != nil {
  662. return err
  663. }
  664. }
  665. return nil
  666. }
  667. seqNrs, err := fetchSequenceNumbers(bucket)
  668. if err != nil {
  669. return err
  670. }
  671. if err := payments.DeleteNestedBucket(paymentHash[:]); err != nil {
  672. return err
  673. }
  674. indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
  675. for _, k := range seqNrs {
  676. if err := indexBucket.Delete(k); err != nil {
  677. return err
  678. }
  679. }
  680. return nil
  681. }, func() {})
  682. }
  683. // DeletePayments deletes all completed and failed payments from the DB. If
  684. // failedOnly is set, only failed payments will be considered for deletion. If
  685. // failedHtlsOnly is set, the payment itself won't be deleted, only failed HTLC
  686. // attempts.
  687. func (d *DB) DeletePayments(failedOnly, failedHtlcsOnly bool) error {
  688. return kvdb.Update(d, func(tx kvdb.RwTx) error {
  689. payments := tx.ReadWriteBucket(paymentsRootBucket)
  690. if payments == nil {
  691. return nil
  692. }
  693. var (
  694. // deleteBuckets is the set of payment buckets we need
  695. // to delete.
  696. deleteBuckets [][]byte
  697. // deleteIndexes is the set of indexes pointing to these
  698. // payments that need to be deleted.
  699. deleteIndexes [][]byte
  700. // deleteHtlcs maps a payment hash to the HTLC IDs we
  701. // want to delete for that payment.
  702. deleteHtlcs = make(map[lntypes.Hash][][]byte)
  703. )
  704. err := payments.ForEach(func(k, _ []byte) error {
  705. bucket := payments.NestedReadBucket(k)
  706. if bucket == nil {
  707. // We only expect sub-buckets to be found in
  708. // this top-level bucket.
  709. return fmt.Errorf("non bucket element in " +
  710. "payments bucket")
  711. }
  712. // If the status is InFlight, we cannot safely delete
  713. // the payment information, so we return early.
  714. paymentStatus, err := fetchPaymentStatus(bucket)
  715. if err != nil {
  716. return err
  717. }
  718. // If the payment has inflight HTLCs, we cannot safely
  719. // delete the payment information, so we return an nil
  720. // to skip it.
  721. if err := paymentStatus.removable(); err != nil {
  722. return nil
  723. }
  724. // If we requested to only delete failed payments, we
  725. // can return if this one is not.
  726. if failedOnly && paymentStatus != StatusFailed {
  727. return nil
  728. }
  729. // If we are only deleting failed HTLCs, fetch them.
  730. if failedHtlcsOnly {
  731. toDelete, err := fetchFailedHtlcKeys(bucket)
  732. if err != nil {
  733. return err
  734. }
  735. hash, err := lntypes.MakeHash(k)
  736. if err != nil {
  737. return err
  738. }
  739. deleteHtlcs[hash] = toDelete
  740. // We return, we are only deleting attempts.
  741. return nil
  742. }
  743. // Add the bucket to the set of buckets we can delete.
  744. deleteBuckets = append(deleteBuckets, k)
  745. // Get all the sequence number associated with the
  746. // payment, including duplicates.
  747. seqNrs, err := fetchSequenceNumbers(bucket)
  748. if err != nil {
  749. return err
  750. }
  751. deleteIndexes = append(deleteIndexes, seqNrs...)
  752. return nil
  753. })
  754. if err != nil {
  755. return err
  756. }
  757. // Delete the failed HTLC attempts we found.
  758. for hash, htlcIDs := range deleteHtlcs {
  759. bucket := payments.NestedReadWriteBucket(hash[:])
  760. htlcsBucket := bucket.NestedReadWriteBucket(
  761. paymentHtlcsBucket,
  762. )
  763. for _, aid := range htlcIDs {
  764. if err := htlcsBucket.Delete(
  765. htlcBucketKey(htlcAttemptInfoKey, aid),
  766. ); err != nil {
  767. return err
  768. }
  769. if err := htlcsBucket.Delete(
  770. htlcBucketKey(htlcFailInfoKey, aid),
  771. ); err != nil {
  772. return err
  773. }
  774. if err := htlcsBucket.Delete(
  775. htlcBucketKey(htlcSettleInfoKey, aid),
  776. ); err != nil {
  777. return err
  778. }
  779. }
  780. }
  781. for _, k := range deleteBuckets {
  782. if err := payments.DeleteNestedBucket(k); err != nil {
  783. return err
  784. }
  785. }
  786. // Get our index bucket and delete all indexes pointing to the
  787. // payments we are deleting.
  788. indexBucket := tx.ReadWriteBucket(paymentsIndexBucket)
  789. for _, k := range deleteIndexes {
  790. if err := indexBucket.Delete(k); err != nil {
  791. return err
  792. }
  793. }
  794. return nil
  795. }, func() {})
  796. }
  797. // fetchSequenceNumbers fetches all the sequence numbers associated with a
  798. // payment, including those belonging to any duplicate payments.
  799. func fetchSequenceNumbers(paymentBucket kvdb.RBucket) ([][]byte, error) {
  800. seqNum := paymentBucket.Get(paymentSequenceKey)
  801. if seqNum == nil {
  802. return nil, errors.New("expected sequence number")
  803. }
  804. sequenceNumbers := [][]byte{seqNum}
  805. // Get the duplicate payments bucket, if it has no duplicates, just
  806. // return early with the payment sequence number.
  807. duplicates := paymentBucket.NestedReadBucket(duplicatePaymentsBucket)
  808. if duplicates == nil {
  809. return sequenceNumbers, nil
  810. }
  811. // If we do have duplicated, they are keyed by sequence number, so we
  812. // iterate through the duplicates bucket and add them to our set of
  813. // sequence numbers.
  814. if err := duplicates.ForEach(func(k, v []byte) error {
  815. sequenceNumbers = append(sequenceNumbers, k)
  816. return nil
  817. }); err != nil {
  818. return nil, err
  819. }
  820. return sequenceNumbers, nil
  821. }
  822. // nolint: dupl
  823. func serializePaymentCreationInfo(w io.Writer, c *PaymentCreationInfo) error {
  824. var scratch [8]byte
  825. if _, err := w.Write(c.PaymentIdentifier[:]); err != nil {
  826. return err
  827. }
  828. byteOrder.PutUint64(scratch[:], uint64(c.Value))
  829. if _, err := w.Write(scratch[:]); err != nil {
  830. return err
  831. }
  832. if err := serializeTime(w, c.CreationTime); err != nil {
  833. return err
  834. }
  835. byteOrder.PutUint32(scratch[:4], uint32(len(c.PaymentRequest)))
  836. if _, err := w.Write(scratch[:4]); err != nil {
  837. return err
  838. }
  839. if _, err := w.Write(c.PaymentRequest[:]); err != nil {
  840. return err
  841. }
  842. return nil
  843. }
  844. func deserializePaymentCreationInfo(r io.Reader) (*PaymentCreationInfo, error) {
  845. var scratch [8]byte
  846. c := &PaymentCreationInfo{}
  847. if _, err := io.ReadFull(r, c.PaymentIdentifier[:]); err != nil {
  848. return nil, err
  849. }
  850. if _, err := io.ReadFull(r, scratch[:]); err != nil {
  851. return nil, err
  852. }
  853. c.Value = lnwire.MilliSatoshi(byteOrder.Uint64(scratch[:]))
  854. creationTime, err := deserializeTime(r)
  855. if err != nil {
  856. return nil, err
  857. }
  858. c.CreationTime = creationTime
  859. if _, err := io.ReadFull(r, scratch[:4]); err != nil {
  860. return nil, err
  861. }
  862. reqLen := uint32(byteOrder.Uint32(scratch[:4]))
  863. payReq := make([]byte, reqLen)
  864. if reqLen > 0 {
  865. if _, err := io.ReadFull(r, payReq); err != nil {
  866. return nil, err
  867. }
  868. }
  869. c.PaymentRequest = payReq
  870. return c, nil
  871. }
  872. func serializeHTLCAttemptInfo(w io.Writer, a *HTLCAttemptInfo) error {
  873. if err := WriteElements(w, a.sessionKey); err != nil {
  874. return err
  875. }
  876. if err := SerializeRoute(w, a.Route); err != nil {
  877. return err
  878. }
  879. if err := serializeTime(w, a.AttemptTime); err != nil {
  880. return err
  881. }
  882. // If the hash is nil we can just return.
  883. if a.Hash == nil {
  884. return nil
  885. }
  886. if _, err := w.Write(a.Hash[:]); err != nil {
  887. return err
  888. }
  889. return nil
  890. }
  891. func deserializeHTLCAttemptInfo(r io.Reader) (*HTLCAttemptInfo, error) {
  892. a := &HTLCAttemptInfo{}
  893. err := ReadElements(r, &a.sessionKey)
  894. if err != nil {
  895. return nil, err
  896. }
  897. a.Route, err = DeserializeRoute(r)
  898. if err != nil {
  899. return nil, err
  900. }
  901. a.AttemptTime, err = deserializeTime(r)
  902. if err != nil {
  903. return nil, err
  904. }
  905. hash := lntypes.Hash{}
  906. _, err = io.ReadFull(r, hash[:])
  907. switch {
  908. // Older payment attempts wouldn't have the hash set, in which case we
  909. // can just return.
  910. case err == io.EOF, err == io.ErrUnexpectedEOF:
  911. return a, nil
  912. case err != nil:
  913. return nil, err
  914. default:
  915. }
  916. a.Hash = &hash
  917. return a, nil
  918. }
  919. func serializeHop(w io.Writer, h *route.Hop) error {
  920. if err := WriteElements(w,
  921. h.PubKeyBytes[:],
  922. h.ChannelID,
  923. h.OutgoingTimeLock,
  924. h.AmtToForward,
  925. ); err != nil {
  926. return err
  927. }
  928. if err := binary.Write(w, byteOrder, h.LegacyPayload); err != nil {
  929. return err
  930. }
  931. // For legacy payloads, we don't need to write any TLV records, so
  932. // we'll write a zero indicating the our serialized TLV map has no
  933. // records.
  934. if h.LegacyPayload {
  935. return WriteElements(w, uint32(0))
  936. }
  937. // Gather all non-primitive TLV records so that they can be serialized
  938. // as a single blob.
  939. //
  940. // TODO(conner): add migration to unify all fields in a single TLV
  941. // blobs. The split approach will cause headaches down the road as more
  942. // fields are added, which we can avoid by having a single TLV stream
  943. // for all payload fields.
  944. var records []tlv.Record
  945. if h.MPP != nil {
  946. records = append(records, h.MPP.Record())
  947. }
  948. // Add blinding point and encrypted data if present.
  949. if h.EncryptedData != nil {
  950. records = append(records, record.NewEncryptedDataRecord(
  951. &h.EncryptedData,
  952. ))
  953. }
  954. if h.BlindingPoint != nil {
  955. records = append(records, record.NewBlindingPointRecord(
  956. &h.BlindingPoint,
  957. ))
  958. }
  959. if h.AMP != nil {
  960. records = append(records, h.AMP.Record())
  961. }
  962. if h.Metadata != nil {
  963. records = append(records, record.NewMetadataRecord(&h.Metadata))
  964. }
  965. if h.TotalAmtMsat != 0 {
  966. totalMsatInt := uint64(h.TotalAmtMsat)
  967. records = append(
  968. records, record.NewTotalAmtMsatBlinded(&totalMsatInt),
  969. )
  970. }
  971. // Final sanity check to absolutely rule out custom records that are not
  972. // custom and write into the standard range.
  973. if err := h.CustomRecords.Validate(); err != nil {
  974. return err
  975. }
  976. // Convert custom records to tlv and add to the record list.
  977. // MapToRecords sorts the list, so adding it here will keep the list
  978. // canonical.
  979. tlvRecords := tlv.MapToRecords(h.CustomRecords)
  980. records = append(records, tlvRecords...)
  981. // Otherwise, we'll transform our slice of records into a map of the
  982. // raw bytes, then serialize them in-line with a length (number of
  983. // elements) prefix.
  984. mapRecords, err := tlv.RecordsToMap(records)
  985. if err != nil {
  986. return err
  987. }
  988. numRecords := uint32(len(mapRecords))
  989. if err := WriteElements(w, numRecords); err != nil {
  990. return err
  991. }
  992. for recordType, rawBytes := range mapRecords {
  993. if err := WriteElements(w, recordType); err != nil {
  994. return err
  995. }
  996. if err := wire.WriteVarBytes(w, 0, rawBytes); err != nil {
  997. return err
  998. }
  999. }
  1000. return nil
  1001. }
  1002. // maxOnionPayloadSize is the largest Sphinx payload possible, so we don't need
  1003. // to read/write a TLV stream larger than this.
  1004. const maxOnionPayloadSize = 1300
  1005. func deserializeHop(r io.Reader) (*route.Hop, error) {
  1006. h := &route.Hop{}
  1007. var pub []byte
  1008. if err := ReadElements(r, &pub); err != nil {
  1009. return nil, err
  1010. }
  1011. copy(h.PubKeyBytes[:], pub)
  1012. if err := ReadElements(r,
  1013. &h.ChannelID, &h.OutgoingTimeLock, &h.AmtToForward,
  1014. ); err != nil {
  1015. return nil, err
  1016. }
  1017. // TODO(roasbeef): change field to allow LegacyPayload false to be the
  1018. // legacy default?
  1019. err := binary.Read(r, byteOrder, &h.LegacyPayload)
  1020. if err != nil {
  1021. return nil, err
  1022. }
  1023. var numElements uint32
  1024. if err := ReadElements(r, &numElements); err != nil {
  1025. return nil, err
  1026. }
  1027. // If there're no elements, then we can return early.
  1028. if numElements == 0 {
  1029. return h, nil
  1030. }
  1031. tlvMap := make(map[uint64][]byte)
  1032. for i := uint32(0); i < numElements; i++ {
  1033. var tlvType uint64
  1034. if err := ReadElements(r, &tlvType); err != nil {
  1035. return nil, err
  1036. }
  1037. rawRecordBytes, err := wire.ReadVarBytes(
  1038. r, 0, maxOnionPayloadSize, "tlv",
  1039. )
  1040. if err != nil {
  1041. return nil, err
  1042. }
  1043. tlvMap[tlvType] = rawRecordBytes
  1044. }
  1045. // If the MPP type is present, remove it from the generic TLV map and
  1046. // parse it back into a proper MPP struct.
  1047. //
  1048. // TODO(conner): add migration to unify all fields in a single TLV
  1049. // blobs. The split approach will cause headaches down the road as more
  1050. // fields are added, which we can avoid by having a single TLV stream
  1051. // for all payload fields.
  1052. mppType := uint64(record.MPPOnionType)
  1053. if mppBytes, ok := tlvMap[mppType]; ok {
  1054. delete(tlvMap, mppType)
  1055. var (
  1056. mpp = &record.MPP{}
  1057. mppRec = mpp.Record()
  1058. r = bytes.NewReader(mppBytes)
  1059. )
  1060. err := mppRec.Decode(r, uint64(len(mppBytes)))
  1061. if err != nil {
  1062. return nil, err
  1063. }
  1064. h.MPP = mpp
  1065. }
  1066. // If encrypted data or blinding key are present, remove them from
  1067. // the TLV map and parse into proper types.
  1068. encryptedDataType := uint64(record.EncryptedDataOnionType)
  1069. if data, ok := tlvMap[encryptedDataType]; ok {
  1070. delete(tlvMap, encryptedDataType)
  1071. h.EncryptedData = data
  1072. }
  1073. blindingType := uint64(record.BlindingPointOnionType)
  1074. if blindingPoint, ok := tlvMap[blindingType]; ok {
  1075. delete(tlvMap, blindingType)
  1076. h.BlindingPoint, err = btcec.ParsePubKey(blindingPoint)
  1077. if err != nil {
  1078. return nil, fmt.Errorf("invalid blinding point: %w",
  1079. err)
  1080. }
  1081. }
  1082. ampType := uint64(record.AMPOnionType)
  1083. if ampBytes, ok := tlvMap[ampType]; ok {
  1084. delete(tlvMap, ampType)
  1085. var (
  1086. amp = &record.AMP{}
  1087. ampRec = amp.Record()
  1088. r = bytes.NewReader(ampBytes)
  1089. )
  1090. err := ampRec.Decode(r, uint64(len(ampBytes)))
  1091. if err != nil {
  1092. return nil, err
  1093. }
  1094. h.AMP = amp
  1095. }
  1096. // If the metadata type is present, remove it from the tlv map and
  1097. // populate directly on the hop.
  1098. metadataType := uint64(record.MetadataOnionType)
  1099. if metadata, ok := tlvMap[metadataType]; ok {
  1100. delete(tlvMap, metadataType)
  1101. h.Metadata = metadata
  1102. }
  1103. totalAmtMsatType := uint64(record.TotalAmtMsatBlindedType)
  1104. if totalAmtMsat, ok := tlvMap[totalAmtMsatType]; ok {
  1105. delete(tlvMap, totalAmtMsatType)
  1106. var (
  1107. totalAmtMsatInt uint64
  1108. buf [8]byte
  1109. )
  1110. if err := tlv.DTUint64(
  1111. bytes.NewReader(totalAmtMsat),
  1112. &totalAmtMsatInt,
  1113. &buf,
  1114. uint64(len(totalAmtMsat)),
  1115. ); err != nil {
  1116. return nil, err
  1117. }
  1118. h.TotalAmtMsat = lnwire.MilliSatoshi(totalAmtMsatInt)
  1119. }
  1120. h.CustomRecords = tlvMap
  1121. return h, nil
  1122. }
  1123. // SerializeRoute serializes a route.
  1124. func SerializeRoute(w io.Writer, r route.Route) error {
  1125. if err := WriteElements(w,
  1126. r.TotalTimeLock, r.TotalAmount, r.SourcePubKey[:],
  1127. ); err != nil {
  1128. return err
  1129. }
  1130. if err := WriteElements(w, uint32(len(r.Hops))); err != nil {
  1131. return err
  1132. }
  1133. for _, h := range r.Hops {
  1134. if err := serializeHop(w, h); err != nil {
  1135. return err
  1136. }
  1137. }
  1138. return nil
  1139. }
  1140. // DeserializeRoute deserializes a route.
  1141. func DeserializeRoute(r io.Reader) (route.Route, error) {
  1142. rt := route.Route{}
  1143. if err := ReadElements(r,
  1144. &rt.TotalTimeLock, &rt.TotalAmount,
  1145. ); err != nil {
  1146. return rt, err
  1147. }
  1148. var pub []byte
  1149. if err := ReadElements(r, &pub); err != nil {
  1150. return rt, err
  1151. }
  1152. copy(rt.SourcePubKey[:], pub)
  1153. var numHops uint32
  1154. if err := ReadElements(r, &numHops); err != nil {
  1155. return rt, err
  1156. }
  1157. var hops []*route.Hop
  1158. for i := uint32(0); i < numHops; i++ {
  1159. hop, err := deserializeHop(r)
  1160. if err != nil {
  1161. return rt, err
  1162. }
  1163. hops = append(hops, hop)
  1164. }
  1165. rt.Hops = hops
  1166. return rt, nil
  1167. }