github.com/JFJun/bsc@v1.0.0/les/checkpointoracle/oracle.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 checkpointoracle is a wrapper of checkpoint oracle contract with
    18  // additional rules defined. This package can be used both in LES client or
    19  // server side for offering oracle related APIs.
    20  package checkpointoracle
    21  
    22  import (
    23  	"encoding/binary"
    24  	"sync/atomic"
    25  
    26  	"github.com/JFJun/bsc/accounts/abi/bind"
    27  	"github.com/JFJun/bsc/common"
    28  	"github.com/JFJun/bsc/contracts/checkpointoracle"
    29  	"github.com/JFJun/bsc/crypto"
    30  	"github.com/JFJun/bsc/log"
    31  	"github.com/JFJun/bsc/params"
    32  )
    33  
    34  // CheckpointOracle is responsible for offering the latest stable checkpoint
    35  // generated and announced by the contract admins on-chain. The checkpoint can
    36  // be verified by clients locally during the checkpoint syncing.
    37  type CheckpointOracle struct {
    38  	config   *params.CheckpointOracleConfig
    39  	contract *checkpointoracle.CheckpointOracle
    40  
    41  	running  int32                                 // Flag whether the contract backend is set or not
    42  	getLocal func(uint64) params.TrustedCheckpoint // Function used to retrieve local checkpoint
    43  }
    44  
    45  // New creates a checkpoint oracle handler with given configs and callback.
    46  func New(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 contract backend, initializes the oracle instance
    64  // and marks the status as available.
    65  func (oracle *CheckpointOracle) Start(backend bind.ContractBackend) {
    66  	contract, err := checkpointoracle.NewCheckpointOracle(oracle.config.Address, backend)
    67  	if err != nil {
    68  		log.Error("Oracle contract binding failed", "err", err)
    69  		return
    70  	}
    71  	if !atomic.CompareAndSwapInt32(&oracle.running, 0, 1) {
    72  		log.Error("Already bound and listening to registrar")
    73  		return
    74  	}
    75  	oracle.contract = contract
    76  }
    77  
    78  // IsRunning returns an indicator whether the oracle is running.
    79  func (oracle *CheckpointOracle) IsRunning() bool {
    80  	return atomic.LoadInt32(&oracle.running) == 1
    81  }
    82  
    83  // Contract returns the underlying raw checkpoint oracle contract.
    84  func (oracle *CheckpointOracle) Contract() *checkpointoracle.CheckpointOracle {
    85  	return oracle.contract
    86  }
    87  
    88  // StableCheckpoint returns the stable checkpoint which was generated by local
    89  // indexers and announced by trusted signers.
    90  func (oracle *CheckpointOracle) StableCheckpoint() (*params.TrustedCheckpoint, uint64) {
    91  	// Retrieve the latest checkpoint from the contract, abort if empty
    92  	latest, hash, height, err := oracle.contract.Contract().GetLatestCheckpoint(nil)
    93  	if err != nil || (latest == 0 && hash == [32]byte{}) {
    94  		return nil, 0
    95  	}
    96  	local := oracle.getLocal(latest)
    97  
    98  	// The following scenarios may occur:
    99  	//
   100  	// * local node is out of sync so that it doesn't have the
   101  	//   checkpoint which registered in the contract.
   102  	// * local checkpoint doesn't match with the registered one.
   103  	//
   104  	// In both cases, no stable checkpoint will be returned.
   105  	if local.HashEqual(hash) {
   106  		return &local, height.Uint64()
   107  	}
   108  	return nil, 0
   109  }
   110  
   111  // VerifySigners recovers the signer addresses according to the signature and
   112  // checks whether there are enough approvals to finalize the checkpoint.
   113  func (oracle *CheckpointOracle) VerifySigners(index uint64, hash [32]byte, signatures [][]byte) (bool, []common.Address) {
   114  	// Short circuit if the given signatures doesn't reach the threshold.
   115  	if len(signatures) < int(oracle.config.Threshold) {
   116  		return false, nil
   117  	}
   118  	var (
   119  		signers []common.Address
   120  		checked = make(map[common.Address]struct{})
   121  	)
   122  	for i := 0; i < len(signatures); i++ {
   123  		if len(signatures[i]) != 65 {
   124  			continue
   125  		}
   126  		// EIP 191 style signatures
   127  		//
   128  		// Arguments when calculating hash to validate
   129  		// 1: byte(0x19) - the initial 0x19 byte
   130  		// 2: byte(0) - the version byte (data with intended validator)
   131  		// 3: this - the validator address
   132  		// --  Application specific data
   133  		// 4 : checkpoint section_index (uint64)
   134  		// 5 : checkpoint hash (bytes32)
   135  		//     hash = keccak256(checkpoint_index, section_head, cht_root, bloom_root)
   136  		buf := make([]byte, 8)
   137  		binary.BigEndian.PutUint64(buf, index)
   138  		data := append([]byte{0x19, 0x00}, append(oracle.config.Address.Bytes(), append(buf, hash[:]...)...)...)
   139  		signatures[i][64] -= 27 // Transform V from 27/28 to 0/1 according to the yellow paper for verification.
   140  		pubkey, err := crypto.Ecrecover(crypto.Keccak256(data), signatures[i])
   141  		if err != nil {
   142  			return false, nil
   143  		}
   144  		var signer common.Address
   145  		copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
   146  		if _, exist := checked[signer]; exist {
   147  			continue
   148  		}
   149  		for _, s := range oracle.config.Signers {
   150  			if s == signer {
   151  				signers = append(signers, signer)
   152  				checked[signer] = struct{}{}
   153  			}
   154  		}
   155  	}
   156  	threshold := oracle.config.Threshold
   157  	if uint64(len(signers)) < threshold {
   158  		log.Warn("Not enough signers to approve checkpoint", "signers", len(signers), "threshold", threshold)
   159  		return false, nil
   160  	}
   161  	return true, signers
   162  }