transaction_util.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package core
  2. import (
  3. "github.com/ethereum/go-ethereum/common"
  4. "github.com/ethereum/go-ethereum/core/types"
  5. "github.com/ethereum/go-ethereum/logger"
  6. "github.com/ethereum/go-ethereum/logger/glog"
  7. "github.com/ethereum/go-ethereum/rlp"
  8. )
  9. var receiptsPre = []byte("receipts-")
  10. // PutTransactions stores the transactions in the given database
  11. func PutTransactions(db common.Database, block *types.Block, txs types.Transactions) {
  12. for i, tx := range block.Transactions() {
  13. rlpEnc, err := rlp.EncodeToBytes(tx)
  14. if err != nil {
  15. glog.V(logger.Debug).Infoln("Failed encoding tx", err)
  16. return
  17. }
  18. db.Put(tx.Hash().Bytes(), rlpEnc)
  19. var txExtra struct {
  20. BlockHash common.Hash
  21. BlockIndex uint64
  22. Index uint64
  23. }
  24. txExtra.BlockHash = block.Hash()
  25. txExtra.BlockIndex = block.NumberU64()
  26. txExtra.Index = uint64(i)
  27. rlpMeta, err := rlp.EncodeToBytes(txExtra)
  28. if err != nil {
  29. glog.V(logger.Debug).Infoln("Failed encoding tx meta data", err)
  30. return
  31. }
  32. db.Put(append(tx.Hash().Bytes(), 0x0001), rlpMeta)
  33. }
  34. }
  35. // PutReceipts stores the receipts in the current database
  36. func PutReceipts(db common.Database, receipts types.Receipts) error {
  37. for _, receipt := range receipts {
  38. storageReceipt := (*types.ReceiptForStorage)(receipt)
  39. bytes, err := rlp.EncodeToBytes(storageReceipt)
  40. if err != nil {
  41. return err
  42. }
  43. err = db.Put(append(receiptsPre, receipt.TxHash[:]...), bytes)
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. return nil
  49. }
  50. // GetReceipt returns a receipt by hash
  51. func GetReceipt(db common.Database, txHash common.Hash) *types.Receipt {
  52. data, _ := db.Get(append(receiptsPre, txHash[:]...))
  53. if len(data) == 0 {
  54. return nil
  55. }
  56. var receipt types.Receipt
  57. err := rlp.DecodeBytes(data, &receipt)
  58. if err != nil {
  59. glog.V(logger.Error).Infoln("GetReceipt err:", err)
  60. }
  61. return &receipt
  62. }
  63. // GetReceiptFromBlock returns all receipts with the given block
  64. func GetReceiptsFromBlock(db common.Database, block *types.Block) types.Receipts {
  65. // at some point we want:
  66. //receipts := make(types.Receipts, len(block.Transactions()))
  67. // but since we need to support legacy, we can't (yet)
  68. var receipts types.Receipts
  69. for _, tx := range block.Transactions() {
  70. if receipt := GetReceipt(db, tx.Hash()); receipt != nil {
  71. receipts = append(receipts, receipt)
  72. }
  73. }
  74. return receipts
  75. }