github.com/tdcblockchain/tdcblockchain@v0.0.0-20191111034745-805c65ade158/les/checkpointoracle.go (about)

     1  // Copyright 2019 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum 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 go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package les
    18  
    19  import (
    20  	"encoding/binary"
    21  	"sync/atomic"
    22  
    23  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/contracts/checkpointoracle"
    26  	"github.com/ethereum/go-ethereum/crypto"
    27  	"github.com/ethereum/go-ethereum/log"
    28  	"github.com/ethereum/go-ethereum/params"
    29  )
    30  
    31  // checkpointOracle is responsible for offering the latest stable checkpoint
    32  // generated and announced by the contract admins on-chain. The checkpoint is
    33  // verified by clients locally during the checkpoint syncing.
    34  type checkpointOracle struct {
    35  	config   *params.CheckpointOracleConfig
    36  	contract *checkpointoracle.CheckpointOracle
    37  
    38  	// Whether the contract backend is set.
    39  	running int32
    40  
    41  	getLocal     func(uint64) params.TrustedCheckpoint // Function used to retrieve local checkpoint
    42  	syncDoneHook func()                                // Function used to notify that light syncing has completed.
    43  }
    44  
    45  // newCheckpointOracle returns a checkpoint registrar handler.
    46  func newCheckpointOracle(config *params.CheckpointOracleConfig, getLocal func(uint64) params.TrustedCheckpoint) *checkpointOracle {
    47  	if config == nil {
    48  		log.Info("Checkpoint registrar is not enabled")
    49  		return nil
    50  	}
    51  	if config.Address == (common.Address{}) || uint64(len(config.Signers)) < config.Threshold {
    52  		log.Warn("Invalid checkpoint registrar config")
    53  		return nil
    54  	}
    55  	log.Info("Configured checkpoint registrar", "address", config.Address, "signers", len(config.Signers), "threshold", config.Threshold)
    56  
    57  	return &checkpointOracle{
    58  		config:   config,
    59  		getLocal: getLocal,
    60  	}
    61  }
    62  
    63  // start binds the registrar contract and start listening to the
    64  // newCheckpointEvent for the server side.
    65  func (reg *checkpointOracle) start(backend bind.ContractBackend) {
    66  	contract, err := checkpointoracle.NewCheckpointOracle(reg.config.Address, backend)
    67  	if err != nil {
    68  		log.Error("Oracle contract binding failed", "err", err)
    69  		return
    70  	}
    71  	if !atomic.CompareAndSwapInt32(&reg.running, 0, 1) {
    72  		log.Error("Already bound and listening to registrar")
    73  		return
    74  	}
    75  	reg.contract = contract
    76  }
    77  
    78  // isRunning returns an indicator whether the registrar is running.
    79  func (reg *checkpointOracle) isRunning() bool {
    80  	return atomic.LoadInt32(&reg.running) == 1
    81  }
    82  
    83  // stableCheckpoint returns the stable checkpoint which was generated by local
    84  // indexers and announced by trusted signers.
    85  func (reg *checkpointOracle) stableCheckpoint() (*params.TrustedCheckpoint, uint64) {
    86  	// Retrieve the latest checkpoint from the contract, abort if empty
    87  	latest, hash, height, err := reg.contract.Contract().GetLatestCheckpoint(nil)
    88  	if err != nil || (latest == 0 && hash == [32]byte{}) {
    89  		return nil, 0
    90  	}
    91  	local := reg.getLocal(latest)
    92  
    93  	// The following scenarios may occur:
    94  	//
    95  	// * local node is out of sync so that it doesn't have the
    96  	//   checkpoint which registered in the contract.
    97  	// * local checkpoint doesn't match with the registered one.
    98  	//
    99  	// In both cases, server won't send the **stable** checkpoint
   100  	// to the client(no worry, client can use hardcoded one instead).
   101  	if local.HashEqual(common.Hash(hash)) {
   102  		return &local, height.Uint64()
   103  	}
   104  	return nil, 0
   105  }
   106  
   107  // verifySigners recovers the signer addresses according to the signature and
   108  // checks whether there are enough approvals to finalize the checkpoint.
   109  func (reg *checkpointOracle) verifySigners(index uint64, hash [32]byte, signatures [][]byte) (bool, []common.Address) {
   110  	// Short circuit if the given signatures doesn't reach the threshold.
   111  	if len(signatures) < int(reg.config.Threshold) {
   112  		return false, nil
   113  	}
   114  	var (
   115  		signers []common.Address
   116  		checked = make(map[common.Address]struct{})
   117  	)
   118  	for i := 0; i < len(signatures); i++ {
   119  		if len(signatures[i]) != 65 {
   120  			continue
   121  		}
   122  		// EIP 191 style signatures
   123  		//
   124  		// Arguments when calculating hash to validate
   125  		// 1: byte(0x19) - the initial 0x19 byte
   126  		// 2: byte(0) - the version byte (data with intended validator)
   127  		// 3: this - the validator address
   128  		// --  Application specific data
   129  		// 4 : checkpoint section_index (uint64)
   130  		// 5 : checkpoint hash (bytes32)
   131  		//     hash = keccak256(checkpoint_index, section_head, cht_root, bloom_root)
   132  		buf := make([]byte, 8)
   133  		binary.BigEndian.PutUint64(buf, index)
   134  		data := append([]byte{0x19, 0x00}, append(reg.config.Address.Bytes(), append(buf, hash[:]...)...)...)
   135  		signatures[i][64] -= 27 // Transform V from 27/28 to 0/1 according to the yellow paper for verification.
   136  		pubkey, err := crypto.Ecrecover(crypto.Keccak256(data), signatures[i])
   137  		if err != nil {
   138  			return false, nil
   139  		}
   140  		var signer common.Address
   141  		copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
   142  		if _, exist := checked[signer]; exist {
   143  			continue
   144  		}
   145  		for _, s := range reg.config.Signers {
   146  			if s == signer {
   147  				signers = append(signers, signer)
   148  				checked[signer] = struct{}{}
   149  			}
   150  		}
   151  	}
   152  	threshold := reg.config.Threshold
   153  	if uint64(len(signers)) < threshold {
   154  		log.Warn("Not enough signers to approve checkpoint", "signers", len(signers), "threshold", threshold)
   155  		return false, nil
   156  	}
   157  	return true, signers
   158  }