github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/core/tx_journal.go (about)

     1  // Copyright 2017 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The Spectrum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the Spectrum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"errors"
    21  	"io"
    22  	"os"
    23  
    24  	"github.com/SmartMeshFoundation/Spectrum/common"
    25  	"github.com/SmartMeshFoundation/Spectrum/core/types"
    26  	"github.com/SmartMeshFoundation/Spectrum/log"
    27  	"github.com/SmartMeshFoundation/Spectrum/rlp"
    28  )
    29  
    30  // errNoActiveJournal is returned if a transaction is attempted to be inserted
    31  // into the journal, but no such file is currently open.
    32  var errNoActiveJournal = errors.New("no active journal")
    33  
    34  // devNull is a WriteCloser that just discards anything written into it. Its
    35  // goal is to allow the transaction journal to write into a fake journal when
    36  // loading transactions on startup without printing warnings due to no file
    37  // being readt for write.
    38  type devNull struct{}
    39  
    40  func (*devNull) Write(p []byte) (n int, err error) { return len(p), nil }
    41  func (*devNull) Close() error                      { return nil }
    42  
    43  // txJournal is a rotating log of transactions with the aim of storing locally
    44  // created transactions to allow non-executed ones to survive node restarts.
    45  type txJournal struct {
    46  	path   string         // Filesystem path to store the transactions at
    47  	writer io.WriteCloser // Output stream to write new transactions into
    48  }
    49  
    50  // newTxJournal creates a new transaction journal to
    51  func newTxJournal(path string) *txJournal {
    52  	return &txJournal{
    53  		path: path,
    54  	}
    55  }
    56  
    57  // load parses a transaction journal dump from disk, loading its contents into
    58  // the specified pool.
    59  func (journal *txJournal) load(add func(*types.Transaction) error) error {
    60  	// Skip the parsing if the journal file doens't exist at all
    61  	if _, err := os.Stat(journal.path); os.IsNotExist(err) {
    62  		return nil
    63  	}
    64  	// Open the journal for loading any past transactions
    65  	input, err := os.Open(journal.path)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	defer input.Close()
    70  
    71  	// Temporarily discard any journal additions (don't double add on load)
    72  	journal.writer = new(devNull)
    73  	defer func() { journal.writer = nil }()
    74  
    75  	// Inject all transactions from the journal into the pool
    76  	stream := rlp.NewStream(input, 0)
    77  	total, dropped := 0, 0
    78  
    79  	var failure error
    80  	for {
    81  		// Parse the next transaction and terminate on error
    82  		tx := new(types.Transaction)
    83  		if err = stream.Decode(tx); err != nil {
    84  			if err != io.EOF {
    85  				failure = err
    86  			}
    87  			break
    88  		}
    89  		// Import the transaction and bump the appropriate progress counters
    90  		total++
    91  		if err = add(tx); err != nil {
    92  			log.Debug("Failed to add journaled transaction", "err", err)
    93  			dropped++
    94  			continue
    95  		}
    96  	}
    97  	log.Info("Loaded local transaction journal", "transactions", total, "dropped", dropped)
    98  
    99  	return failure
   100  }
   101  
   102  // insert adds the specified transaction to the local disk journal.
   103  func (journal *txJournal) insert(tx *types.Transaction) error {
   104  	if journal.writer == nil {
   105  		return errNoActiveJournal
   106  	}
   107  	if err := rlp.Encode(journal.writer, tx); err != nil {
   108  		return err
   109  	}
   110  	return nil
   111  }
   112  
   113  // TODO liangc : why loop run rotate ??? "Regenerated local transaction journal"
   114  // rotate regenerates the transaction journal based on the current contents of
   115  // the transaction pool.
   116  func (journal *txJournal) rotate(all map[common.Address]types.Transactions) error {
   117  	// Close the current journal (if any is open)
   118  	if journal.writer != nil {
   119  		if err := journal.writer.Close(); err != nil {
   120  			return err
   121  		}
   122  		journal.writer = nil
   123  	}
   124  	// Generate a new journal with the contents of the current pool
   125  	replacement, err := os.OpenFile(journal.path+".new", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
   126  	if err != nil {
   127  		return err
   128  	}
   129  	journaled := 0
   130  	for _, txs := range all {
   131  		for _, tx := range txs {
   132  			if err = rlp.Encode(replacement, tx); err != nil {
   133  				replacement.Close()
   134  				return err
   135  			}
   136  		}
   137  		journaled += len(txs)
   138  	}
   139  	replacement.Close()
   140  
   141  	// Replace the live journal with the newly generated one
   142  	if err = os.Rename(journal.path+".new", journal.path); err != nil {
   143  		return err
   144  	}
   145  	sink, err := os.OpenFile(journal.path, os.O_WRONLY|os.O_APPEND, 0755)
   146  	if err != nil {
   147  		return err
   148  	}
   149  	journal.writer = sink
   150  	log.Info("Regenerated local transaction journal", "transactions", journaled, "accounts", len(all))
   151  
   152  	return nil
   153  }
   154  
   155  // close flushes the transaction journal contents to disk and closes the file.
   156  func (journal *txJournal) close() error {
   157  	var err error
   158  
   159  	if journal.writer != nil {
   160  		err = journal.writer.Close()
   161  		journal.writer = nil
   162  	}
   163  	return err
   164  }