mirror of
https://github.com/kaspanet/kaspad.git
synced 2025-03-30 15:08:33 +00:00
[NOD-754] Fix staticcheck errors (#627)
* [NOD-754] Fix staticcheck errors * [NOD-754] Remove some unused exported functions * [NOD-754] Fix staticcheck errors * [NOD-754] Don't panic if out/in close fails * [NOD-754] Wrap outside errors with custom message
This commit is contained in:
parent
30fe0c279b
commit
a4bb070722
@ -24,9 +24,6 @@ type naTest struct {
|
||||
// method.
|
||||
var naTests = make([]naTest, 0)
|
||||
|
||||
// Put some IP in here for convenience. Points to google.
|
||||
var someIP = "173.194.115.66"
|
||||
|
||||
// addNaTests
|
||||
func addNaTests() {
|
||||
// IPv4
|
||||
|
@ -31,11 +31,6 @@ const (
|
||||
// statusInvalidAncestor indicates that one of the block's ancestors has
|
||||
// has failed validation, thus the block is also invalid.
|
||||
statusInvalidAncestor
|
||||
|
||||
// statusNone indicates that the block has no validation state flags set.
|
||||
//
|
||||
// NOTE: This must be defined last in order to avoid influencing iota.
|
||||
statusNone blockStatus = 0
|
||||
)
|
||||
|
||||
// KnownValid returns whether the block is known to be valid. This will return
|
||||
@ -184,7 +179,7 @@ func (node *blockNode) Header() *wire.BlockHeader {
|
||||
//
|
||||
// This function is safe for concurrent access.
|
||||
func (node *blockNode) SelectedAncestor(blueScore uint64) *blockNode {
|
||||
if blueScore < 0 || blueScore > node.blueScore {
|
||||
if blueScore > node.blueScore {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -102,17 +102,6 @@ func (bs blockSet) String() string {
|
||||
return strings.Join(nodeStrs, ",")
|
||||
}
|
||||
|
||||
// anyChildInSet returns true iff any child of node is contained within this set
|
||||
func (bs blockSet) anyChildInSet(node *blockNode) bool {
|
||||
for child := range node.children {
|
||||
if bs.contains(child) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (bs blockSet) bluest() *blockNode {
|
||||
var bluestNode *blockNode
|
||||
var maxScore uint64
|
||||
|
@ -23,17 +23,6 @@ import (
|
||||
"github.com/kaspanet/kaspad/wire"
|
||||
)
|
||||
|
||||
func loadBlocksWithLog(t *testing.T, filename string) ([]*util.Block, error) {
|
||||
blocks, err := LoadBlocks(filename)
|
||||
if err == nil {
|
||||
t.Logf("Loaded %d blocks from file %s", len(blocks), filename)
|
||||
for i, b := range blocks {
|
||||
t.Logf("Block #%d: %s", i, b.Hash())
|
||||
}
|
||||
}
|
||||
return blocks, err
|
||||
}
|
||||
|
||||
// loadUTXOSet returns a utxo view loaded from a file.
|
||||
func loadUTXOSet(filename string) (UTXOSet, error) {
|
||||
// The utxostore file format is:
|
||||
|
@ -232,9 +232,7 @@ func (dag *BlockDAG) GetOrphanMissingAncestorHashes(orphanHash *daghash.Hash) ([
|
||||
visited[*current] = true
|
||||
orphan, orphanExists := dag.orphans[*current]
|
||||
if orphanExists {
|
||||
for _, parentHash := range orphan.block.MsgBlock().Header.ParentHashes {
|
||||
queue = append(queue, parentHash)
|
||||
}
|
||||
queue = append(queue, orphan.block.MsgBlock().Header.ParentHashes...)
|
||||
} else {
|
||||
if !dag.IsInDAG(current) && current != orphanHash {
|
||||
missingAncestorsHashes = append(missingAncestorsHashes, current)
|
||||
@ -837,16 +835,6 @@ func (dag *BlockDAG) NextBlockCoinbaseTransactionNoLock(scriptPubKey []byte, ext
|
||||
return dag.virtual.blockNode.expectedCoinbaseTransaction(dag, txsAcceptanceData, scriptPubKey, extraData)
|
||||
}
|
||||
|
||||
// NextAcceptedIDMerkleRoot prepares the acceptedIDMerkleRoot for the next mined block
|
||||
//
|
||||
// This function CAN'T be called with the DAG lock held.
|
||||
func (dag *BlockDAG) NextAcceptedIDMerkleRoot() (*daghash.Hash, error) {
|
||||
dag.dagLock.RLock()
|
||||
defer dag.dagLock.RUnlock()
|
||||
|
||||
return dag.NextAcceptedIDMerkleRootNoLock()
|
||||
}
|
||||
|
||||
// NextAcceptedIDMerkleRootNoLock prepares the acceptedIDMerkleRoot for the next mined block
|
||||
//
|
||||
// This function MUST be called with the DAG read-lock held
|
||||
@ -879,18 +867,6 @@ func (dag *BlockDAG) TxsAcceptedByBlockHash(blockHash *daghash.Hash) (MultiBlock
|
||||
return txsAcceptanceData, err
|
||||
}
|
||||
|
||||
// BlockPastUTXO retrieves the past UTXO of this block
|
||||
//
|
||||
// This function MUST be called with the DAG read-lock held
|
||||
func (dag *BlockDAG) BlockPastUTXO(blockHash *daghash.Hash) (UTXOSet, error) {
|
||||
node := dag.index.LookupNode(blockHash)
|
||||
if node == nil {
|
||||
return nil, errors.Errorf("Couldn't find block %s", blockHash)
|
||||
}
|
||||
pastUTXO, _, err := dag.pastUTXO(node)
|
||||
return pastUTXO, err
|
||||
}
|
||||
|
||||
// applyDAGChanges does the following:
|
||||
// 1. Connects each of the new block's parents to the block.
|
||||
// 2. Adds the new block to the DAG's tips.
|
||||
@ -1757,8 +1733,7 @@ func (dag *BlockDAG) GetTopHeaders(highHash *daghash.Hash, maxHeaders uint64) ([
|
||||
|
||||
visited := newSet()
|
||||
for i := uint32(0); queue.Len() > 0 && uint64(len(headers)) < maxHeaders; i++ {
|
||||
var current *blockNode
|
||||
current = queue.pop()
|
||||
current := queue.pop()
|
||||
if !visited.contains(current) {
|
||||
visited.add(current)
|
||||
headers = append(headers, current.Header())
|
||||
|
@ -608,6 +608,9 @@ func (dag *BlockDAG) initDAGState() error {
|
||||
|
||||
// Attempt to accept the block.
|
||||
block, err := dbFetchBlockByNode(dbTx, node)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
isOrphan, isDelayed, err := dag.ProcessBlock(block, BFWasStored)
|
||||
if err != nil {
|
||||
log.Warnf("Block %s, which was not previously processed, "+
|
||||
|
@ -521,6 +521,10 @@ func TestGasLimit(t *testing.T) {
|
||||
if isOrphan {
|
||||
t.Fatalf("ProcessBlock: overLimitBlock got unexpectedly orphan")
|
||||
}
|
||||
if isDelayed {
|
||||
t.Fatalf("ProcessBlock: overflowGasBlock " +
|
||||
"is too far in the future")
|
||||
}
|
||||
|
||||
nonExistentSubnetwork := &subnetworkid.SubnetworkID{123}
|
||||
nonExistentSubnetworkTxIn := &wire.TxIn{
|
||||
@ -547,6 +551,13 @@ func TestGasLimit(t *testing.T) {
|
||||
if err.Error() != expectedErrStr {
|
||||
t.Fatalf("ProcessBlock expected error \"%v\" but got \"%v\"", expectedErrStr, err)
|
||||
}
|
||||
if isDelayed {
|
||||
t.Fatalf("ProcessBlock: nonExistentSubnetworkBlock " +
|
||||
"is too far in the future")
|
||||
}
|
||||
if isOrphan {
|
||||
t.Fatalf("ProcessBlock: nonExistentSubnetworkBlock got unexpectedly orphan")
|
||||
}
|
||||
|
||||
// Here we check that we can process a block with a transaction that doesn't exceed the gas limit
|
||||
validBlock, err := mining.PrepareBlockForTest(dag, ¶ms, dag.TipHashes(), []*wire.MsgTx{tx1}, true)
|
||||
|
@ -298,16 +298,16 @@ func copyDirectory(scrDir, dest string) error {
|
||||
// This function is copied and modified from this stackoverflow answer: https://stackoverflow.com/a/56314145/2413761
|
||||
func copyFile(srcFile, dstFile string) error {
|
||||
out, err := os.Create(dstFile)
|
||||
defer out.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
in, err := os.Open(srcFile)
|
||||
defer in.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
|
||||
_, err = io.Copy(out, in)
|
||||
if err != nil {
|
||||
|
@ -6,8 +6,6 @@ package indexers
|
||||
|
||||
import (
|
||||
"github.com/kaspanet/kaspad/logger"
|
||||
"github.com/kaspanet/kaspad/util/panics"
|
||||
)
|
||||
|
||||
var log, _ = logger.Get(logger.SubsystemTags.INDX)
|
||||
var spawn = panics.GoroutineWrapperFunc(log)
|
||||
|
@ -363,6 +363,9 @@ func dropIndex(db database.DB, idxKey []byte, idxName string, interrupt <-chan s
|
||||
}
|
||||
return bucket.DeleteBucket(bucketName[len(bucketName)-1])
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the index tip, index bucket, and in-progress drop flag now
|
||||
|
@ -316,44 +316,6 @@ func (idx *TxIndex) TxFirstBlockRegion(txID *daghash.TxID) (*database.BlockRegio
|
||||
return region, err
|
||||
}
|
||||
|
||||
// TxBlocks returns the hashes of the blocks where the transaction exists
|
||||
func (idx *TxIndex) TxBlocks(txHash *daghash.Hash) ([]*daghash.Hash, error) {
|
||||
blockHashes := make([]*daghash.Hash, 0)
|
||||
err := idx.db.View(func(dbTx database.Tx) error {
|
||||
var err error
|
||||
blockHashes, err = dbFetchTxBlocks(dbTx, txHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return blockHashes, err
|
||||
}
|
||||
|
||||
func dbFetchTxBlocks(dbTx database.Tx, txHash *daghash.Hash) ([]*daghash.Hash, error) {
|
||||
blockHashes := make([]*daghash.Hash, 0)
|
||||
bucket := dbTx.Metadata().Bucket(includingBlocksIndexKey).Bucket(txHash[:])
|
||||
if bucket == nil {
|
||||
return nil, database.Error{
|
||||
ErrorCode: database.ErrCorruption,
|
||||
Description: fmt.Sprintf("No including blocks "+
|
||||
"were found for %s", txHash),
|
||||
}
|
||||
}
|
||||
err := bucket.ForEach(func(serializedBlockID, _ []byte) error {
|
||||
blockHash, err := blockdag.DBFetchBlockHashBySerializedID(dbTx, serializedBlockID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
blockHashes = append(blockHashes, blockHash)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return blockHashes, nil
|
||||
}
|
||||
|
||||
// BlockThatAcceptedTx returns the hash of the block where the transaction got accepted (from the virtual block point of view)
|
||||
func (idx *TxIndex) BlockThatAcceptedTx(dag *blockdag.BlockDAG, txID *daghash.TxID) (*daghash.Hash, error) {
|
||||
var acceptingBlock *daghash.Hash
|
||||
|
@ -305,9 +305,7 @@ func (rtn *reachabilityTreeNode) countSubtrees(subTreeSizeMap map[*reachabilityT
|
||||
// We haven't yet calculated the subtree size of
|
||||
// the current node. Add all its children to the
|
||||
// queue
|
||||
for _, child := range current.children {
|
||||
queue = append(queue, child)
|
||||
}
|
||||
queue = append(queue, current.children...)
|
||||
continue
|
||||
}
|
||||
|
||||
|
@ -230,9 +230,6 @@ func (dag *BlockDAG) thresholdState(prevNode *blockNode, checker thresholdCondit
|
||||
if condition {
|
||||
count++
|
||||
}
|
||||
|
||||
// Get the previous block node.
|
||||
current = current.selectedParent
|
||||
}
|
||||
|
||||
// The state is locked in if the number of blocks in the
|
||||
|
@ -446,9 +446,9 @@ func (dag *BlockDAG) checkBlockHeaderSanity(header *wire.BlockHeader, flags Beha
|
||||
|
||||
//checkBlockParentsOrder ensures that the block's parents are ordered by hash
|
||||
func checkBlockParentsOrder(header *wire.BlockHeader) error {
|
||||
sortedHashes := make([]*daghash.Hash, 0, header.NumParentBlocks())
|
||||
for _, hash := range header.ParentHashes {
|
||||
sortedHashes = append(sortedHashes, hash)
|
||||
sortedHashes := make([]*daghash.Hash, header.NumParentBlocks())
|
||||
for i, hash := range header.ParentHashes {
|
||||
sortedHashes[i] = hash
|
||||
}
|
||||
sort.Slice(sortedHashes, func(i, j int) bool {
|
||||
return daghash.Less(sortedHashes[i], sortedHashes[j])
|
||||
|
@ -39,15 +39,6 @@ func newVirtualBlock(dag *BlockDAG, tips blockSet) *virtualBlock {
|
||||
return &virtual
|
||||
}
|
||||
|
||||
// clone creates and returns a clone of the virtual block.
|
||||
func (v *virtualBlock) clone() *virtualBlock {
|
||||
return &virtualBlock{
|
||||
utxoSet: v.utxoSet,
|
||||
blockNode: v.blockNode,
|
||||
selectedParentChainSet: v.selectedParentChainSet,
|
||||
}
|
||||
}
|
||||
|
||||
// setTips replaces the tips of the virtual block with the blocks in the
|
||||
// given blockSet. This only differs from the exported version in that it
|
||||
// is up to the caller to ensure the lock is held.
|
||||
|
@ -53,16 +53,10 @@ func parseConfig() (*ConfigFlags, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if activeConfig.GasLimit < 0 {
|
||||
return nil, errors.Errorf("gaslimit may not be smaller than 0")
|
||||
}
|
||||
if activeConfig.GasLimit == 0 {
|
||||
activeConfig.GasLimit = defaultSubnetworkGasLimit
|
||||
}
|
||||
|
||||
if activeConfig.RegistryTxFee < 0 {
|
||||
return nil, errors.Errorf("regtxfee may not be smaller than 0")
|
||||
}
|
||||
if activeConfig.RegistryTxFee == 0 {
|
||||
activeConfig.RegistryTxFee = defaultRegistryTxFee
|
||||
}
|
||||
|
@ -36,11 +36,6 @@ var (
|
||||
activeConfig *ConfigFlags
|
||||
)
|
||||
|
||||
// ActiveConfig returns the active configuration struct
|
||||
func ActiveConfig() *ConfigFlags {
|
||||
return activeConfig
|
||||
}
|
||||
|
||||
// listCommands categorizes and lists all of the usable commands along with
|
||||
// their one-line usage.
|
||||
func listCommands() {
|
||||
|
@ -8,6 +8,7 @@ import (
|
||||
"github.com/kaspanet/kaspad/txscript"
|
||||
"github.com/kaspanet/kaspad/util"
|
||||
"github.com/kaspanet/kaspad/wire"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
@ -53,6 +54,9 @@ func parsePrivateKey(privateKeyHex string) (*ecc.PrivateKey, error) {
|
||||
|
||||
func parseTransaction(transactionHex string) (*wire.MsgTx, error) {
|
||||
serializedTx, err := hex.DecodeString(transactionHex)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "couldn't decode transaction hex")
|
||||
}
|
||||
var transaction wire.MsgTx
|
||||
err = transaction.Deserialize(bytes.NewReader(serializedTx))
|
||||
return &transaction, err
|
||||
@ -60,6 +64,9 @@ func parseTransaction(transactionHex string) (*wire.MsgTx, error) {
|
||||
|
||||
func createScriptPubKey(publicKey *ecc.PublicKey) ([]byte, error) {
|
||||
p2pkhAddress, err := util.NewAddressPubKeyHashFromPublicKey(publicKey.SerializeCompressed(), ActiveConfig().NetParams().Prefix)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scriptPubKey, err := txscript.PayToAddrScript(p2pkhAddress)
|
||||
return scriptPubKey, err
|
||||
}
|
||||
|
@ -79,15 +79,6 @@ var activeConfig *Config
|
||||
// to parse and execute service commands specified via the -s flag.
|
||||
var RunServiceCommand func(string) error
|
||||
|
||||
// minUint32 is a helper function to return the minimum of two uint32s.
|
||||
// This avoids a math import and the need to cast to floats.
|
||||
func minUint32(a, b uint32) uint32 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Flags defines the configuration options for kaspad.
|
||||
//
|
||||
// See loadConfig for details on the configuration load process.
|
||||
@ -591,7 +582,7 @@ func loadConfig() (*Config, []string, error) {
|
||||
}
|
||||
|
||||
// Disallow 0 and negative min tx fees.
|
||||
if activeConfig.MinRelayTxFee <= 0 {
|
||||
if activeConfig.MinRelayTxFee == 0 {
|
||||
str := "%s: The minrelaytxfee option must be greater than 0 -- parsed [%d]"
|
||||
err := errors.Errorf(str, funcName, activeConfig.MinRelayTxFee)
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
|
@ -38,8 +38,8 @@ func TestDynamicBanScoreLifetime(t *testing.T) {
|
||||
var bs DynamicBanScore
|
||||
base := time.Now()
|
||||
|
||||
r := bs.increase(0, math.MaxUint32, base)
|
||||
r = bs.int(base.Add(Lifetime * time.Second))
|
||||
bs.increase(0, math.MaxUint32, base)
|
||||
r := bs.int(base.Add(Lifetime * time.Second))
|
||||
if r != 3 { // 3, not 4 due to precision loss and truncating 3.999...
|
||||
t.Errorf("Pre max age check with MaxUint32 failed - %d", r)
|
||||
}
|
||||
|
@ -12,14 +12,6 @@ import (
|
||||
_ "github.com/kaspanet/kaspad/database/ffldb"
|
||||
)
|
||||
|
||||
var (
|
||||
// ignoreDbTypes are types which should be ignored when running tests
|
||||
// that iterate all supported DB types. This allows some tests to add
|
||||
// bogus drivers for testing purposes while still allowing other tests
|
||||
// to easily iterate all supported drivers.
|
||||
ignoreDbTypes = map[string]bool{"createopenfail": true}
|
||||
)
|
||||
|
||||
// checkDbError ensures the passed error is a database.Error with an error code
|
||||
// that matches the passed error code.
|
||||
func checkDbError(t *testing.T, testName string, gotErr error, wantErrCode database.ErrorCode) bool {
|
||||
|
@ -37,16 +37,6 @@ const (
|
||||
// must be less than 2^32 (4 GiB). This is also why it's a typed
|
||||
// constant.
|
||||
maxBlockFileSize uint32 = 512 * 1024 * 1024 // 512 MiB
|
||||
|
||||
// blockLocSize is the number of bytes the serialized block location
|
||||
// data that is stored in the block index.
|
||||
//
|
||||
// The serialized block location format is:
|
||||
//
|
||||
// [0:4] Block file (4 bytes)
|
||||
// [4:8] File offset (4 bytes)
|
||||
// [8:12] Block length (4 bytes)
|
||||
blockLocSize = 12
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -28,17 +28,8 @@ import (
|
||||
"github.com/kaspanet/kaspad/wire"
|
||||
)
|
||||
|
||||
const (
|
||||
// metadataDbName is the name used for the metadata database.
|
||||
metadataDbName = "metadata"
|
||||
|
||||
// blockHdrOffset defines the offsets into a block index row for the
|
||||
// block header.
|
||||
//
|
||||
// The serialized block index row format is:
|
||||
// <blocklocation><blockheader>
|
||||
blockHdrOffset = blockLocSize
|
||||
)
|
||||
// metadataDbName is the name used for the metadata database.
|
||||
const metadataDbName = "metadata"
|
||||
|
||||
var (
|
||||
// byteOrder is the preferred byte order used through the database and
|
||||
|
@ -24,19 +24,6 @@ const (
|
||||
// threshold in between database cache flushes when the cache size has
|
||||
// not been exceeded.
|
||||
defaultFlushSecs = 300 // 5 minutes
|
||||
|
||||
// ldbBatchHeaderSize is the size of a leveldb batch header which
|
||||
// includes the sequence header and record counter.
|
||||
//
|
||||
// ldbRecordIKeySize is the size of the ikey used internally by leveldb
|
||||
// when appending a record to a batch.
|
||||
//
|
||||
// These are used to help preallocate space needed for a batch in one
|
||||
// allocation instead of letting leveldb itself constantly grow it.
|
||||
// This results in far less pressure on the GC and consequently helps
|
||||
// prevent the GC from allocating a lot of extra unneeded space.
|
||||
ldbBatchHeaderSize = 12
|
||||
ldbRecordIKeySize = 8
|
||||
)
|
||||
|
||||
// ldbCacheIter wraps a treap iterator to provide the additional functionality
|
||||
|
@ -754,7 +754,7 @@ func testMetadataManualTxInterface(tc *testContext) bool {
|
||||
deleteValues := func(values []keyPair) bool {
|
||||
tx, err := tc.db.Begin(true)
|
||||
if err != nil {
|
||||
|
||||
tc.t.Fatalf("tc.db.Begin: %s", err)
|
||||
}
|
||||
defer rollbackOnPanic(tc.t, tx)
|
||||
|
||||
|
@ -6,24 +6,11 @@ package treap
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fromHex converts the passed hex string into a byte slice and will panic if
|
||||
// there is an error. This is only provided for the hard-coded constants so
|
||||
// errors in the source code can be detected. It will only (and must only) be
|
||||
// called for initialization purposes.
|
||||
func fromHex(s string) []byte {
|
||||
r, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
panic("invalid hex in source file: " + s)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// serializeUint32 returns the big-endian encoding of the passed uint32.
|
||||
func serializeUint32(ui uint32) []byte {
|
||||
var ret [4]byte
|
||||
|
@ -1,11 +0,0 @@
|
||||
// Copyright (c) 2013-2016 The btcsuite developers
|
||||
// Use of this source code is governed by an ISC
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package database
|
||||
|
||||
import (
|
||||
"github.com/kaspanet/kaspad/logger"
|
||||
)
|
||||
|
||||
var log, _ = logger.Get(logger.SubsystemTags.BCDB)
|
@ -76,10 +76,6 @@ const (
|
||||
// 2^(fieldBase*i) where i is the word position.
|
||||
fieldBase = 26
|
||||
|
||||
// fieldOverflowBits is the minimum number of "overflow" bits for each
|
||||
// word in the field value.
|
||||
fieldOverflowBits = 32 - fieldBase
|
||||
|
||||
// fieldBaseMask is the mask for the bits in each word needed to
|
||||
// represent the numeric base of each word (except the most significant
|
||||
// word).
|
||||
|
@ -14,12 +14,6 @@ import (
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// Errors returned by canonicalPadding.
|
||||
var (
|
||||
errNegativeValue = errors.New("value may be interpreted as negative")
|
||||
errExcessivelyPaddedValue = errors.New("value is excessively padded")
|
||||
)
|
||||
|
||||
// Signature is a type representing a Schnorr signature.
|
||||
type Signature struct {
|
||||
R *big.Int
|
||||
|
@ -11,13 +11,6 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
type signatureTest struct {
|
||||
name string
|
||||
sig []byte
|
||||
der bool
|
||||
isValid bool
|
||||
}
|
||||
|
||||
// decodeHex decodes the passed hex string and returns the resulting bytes. It
|
||||
// panics if an error occurs. This is only used in the tests as a helper since
|
||||
// the only way it can fail is if there is an error in the test source code.
|
||||
|
@ -148,8 +148,6 @@ type TxPool struct {
|
||||
orphans map[daghash.TxID]*orphanTx
|
||||
orphansByPrev map[wire.Outpoint]map[daghash.TxID]*util.Tx
|
||||
outpoints map[wire.Outpoint]*util.Tx
|
||||
pennyTotal float64 // exponentially decaying total for penny spends.
|
||||
lastPennyUnix int64 // unix time of last ``penny spend''
|
||||
|
||||
// nextExpireScan is the time after which the orphan pool will be
|
||||
// scanned in order to evict orphans. This is NOT a hard deadline as
|
||||
@ -779,9 +777,15 @@ func (mp *TxPool) FetchTransaction(txID *daghash.TxID) (*util.Tx, error) {
|
||||
return nil, errors.Errorf("transaction is not in the pool")
|
||||
}
|
||||
|
||||
// maybeAcceptTransaction is the internal function which implements the public
|
||||
// MaybeAcceptTransaction. See the comment for MaybeAcceptTransaction for
|
||||
// more details.
|
||||
// maybeAcceptTransaction is the main workhorse for handling insertion of new
|
||||
// free-standing transactions into a memory pool. It includes functionality
|
||||
// such as rejecting duplicate transactions, ensuring transactions follow all
|
||||
// rules, detecting orphan transactions, and insertion into the memory pool.
|
||||
//
|
||||
// If the transaction is an orphan (missing parent transactions), the
|
||||
// transaction is NOT added to the orphan pool, but each unknown referenced
|
||||
// parent is returned. Use ProcessTransaction instead if new orphans should
|
||||
// be added to the orphan pool.
|
||||
//
|
||||
// This function MUST be called with the mempool lock held (for writes).
|
||||
func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([]*daghash.TxID, *TxDesc, error) {
|
||||
@ -1029,28 +1033,6 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([]
|
||||
return nil, txD, nil
|
||||
}
|
||||
|
||||
// MaybeAcceptTransaction is the main workhorse for handling insertion of new
|
||||
// free-standing transactions into a memory pool. It includes functionality
|
||||
// such as rejecting duplicate transactions, ensuring transactions follow all
|
||||
// rules, detecting orphan transactions, and insertion into the memory pool.
|
||||
//
|
||||
// If the transaction is an orphan (missing parent transactions), the
|
||||
// transaction is NOT added to the orphan pool, but each unknown referenced
|
||||
// parent is returned. Use ProcessTransaction instead if new orphans should
|
||||
// be added to the orphan pool.
|
||||
//
|
||||
// This function is safe for concurrent access.
|
||||
func (mp *TxPool) MaybeAcceptTransaction(tx *util.Tx, isNew bool) ([]*daghash.TxID, *TxDesc, error) {
|
||||
// Protect concurrent access.
|
||||
mp.cfg.DAG.RLock()
|
||||
defer mp.cfg.DAG.RUnlock()
|
||||
mp.mtx.Lock()
|
||||
defer mp.mtx.Unlock()
|
||||
hashes, txD, err := mp.maybeAcceptTransaction(tx, true)
|
||||
|
||||
return hashes, txD, err
|
||||
}
|
||||
|
||||
// processOrphans is the internal function which implements the public
|
||||
// ProcessOrphans. See the comment for ProcessOrphans for more details.
|
||||
//
|
||||
|
@ -556,6 +556,9 @@ func TestProcessTransaction(t *testing.T) {
|
||||
|
||||
//Checks that non standard transactions are rejected from the mempool
|
||||
nonStdTx, err := harness.createTx(spendableOuts[0], 0, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error from harness.createTx: %s", err)
|
||||
}
|
||||
nonStdTx.MsgTx().Version = wire.TxVersion + 1
|
||||
_, err = harness.txPool.ProcessTransaction(nonStdTx, true, 0)
|
||||
if err == nil {
|
||||
@ -968,14 +971,28 @@ func TestOrphanExpiration(t *testing.T) {
|
||||
amount: util.Amount(5000000000),
|
||||
outpoint: wire.Outpoint{TxID: daghash.TxID{}, Index: 0},
|
||||
}}, 1)
|
||||
harness.txPool.ProcessTransaction(expiredTx, true, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error on harness.CreateSignedTx: %s", err)
|
||||
}
|
||||
|
||||
_, err = harness.txPool.ProcessTransaction(expiredTx, true, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error on harness.ProcessTransaction: %s", err)
|
||||
}
|
||||
harness.txPool.orphans[*expiredTx.ID()].expiration = time.Unix(0, 0)
|
||||
|
||||
tx1, err := harness.CreateSignedTx([]spendableOutpoint{{
|
||||
amount: util.Amount(5000000000),
|
||||
outpoint: wire.Outpoint{TxID: daghash.TxID{1}, Index: 0},
|
||||
}}, 1)
|
||||
harness.txPool.ProcessTransaction(tx1, true, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error on harness.CreateSignedTx: %s", err)
|
||||
}
|
||||
|
||||
_, err = harness.txPool.ProcessTransaction(tx1, true, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error on harness.ProcessTransaction: %s", err)
|
||||
}
|
||||
|
||||
//First check that expired orphan transactions are not removed before nextExpireScan
|
||||
testPoolMembership(tc, tx1, true, false, false)
|
||||
@ -989,7 +1006,13 @@ func TestOrphanExpiration(t *testing.T) {
|
||||
amount: util.Amount(5000000000),
|
||||
outpoint: wire.Outpoint{TxID: daghash.TxID{2}, Index: 0},
|
||||
}}, 1)
|
||||
harness.txPool.ProcessTransaction(tx2, true, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error on harness.CreateSignedTx: %s", err)
|
||||
}
|
||||
_, err = harness.txPool.ProcessTransaction(tx2, true, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error on harness.ProcessTransaction: %s", err)
|
||||
}
|
||||
//Check that only expired orphan transactions are removed
|
||||
testPoolMembership(tc, tx1, true, false, false)
|
||||
testPoolMembership(tc, tx2, true, false, false)
|
||||
|
@ -288,22 +288,15 @@ func (g *BlkTmplGenerator) UpdateExtraNonce(msgBlock *wire.MsgBlock, extraNonce
|
||||
|
||||
return g.buildUTXOCommitment(msgBlock.Transactions)
|
||||
}()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
msgBlock.Header.UTXOCommitment = utxoCommitment
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// VirtualBlueScore returns the virtual block's current blue score
|
||||
func (g *BlkTmplGenerator) VirtualBlueScore() uint64 {
|
||||
return g.dag.VirtualBlueScore()
|
||||
}
|
||||
|
||||
// TipHashes returns the hashes of the DAG's tips
|
||||
func (g *BlkTmplGenerator) TipHashes() []*daghash.Hash {
|
||||
return g.dag.TipHashes()
|
||||
}
|
||||
|
||||
// TxSource returns the associated transaction source.
|
||||
//
|
||||
// This function is safe for concurrent access.
|
||||
|
@ -96,9 +96,7 @@ func PrepareBlockForTest(dag *blockdag.BlockDAG, params *dagconfig.Params, paren
|
||||
}
|
||||
}
|
||||
if forceTransactions && len(txsToAdd) > 0 {
|
||||
for _, tx := range txsToAdd {
|
||||
template.Block.Transactions = append(template.Block.Transactions, tx)
|
||||
}
|
||||
template.Block.Transactions = append(template.Block.Transactions, txsToAdd...)
|
||||
}
|
||||
updateHeaderFields := forceTransactions && len(txsToAdd) > 0
|
||||
if updateHeaderFields {
|
||||
|
@ -254,7 +254,7 @@ func (g *BlkTmplGenerator) populateTemplateFromCandidates(candidateTxs []*candid
|
||||
|
||||
// If isMarkedForDeletion is set, it means we got a collision.
|
||||
// Ignore and select another Tx.
|
||||
if selectedTx.isMarkedForDeletion == true {
|
||||
if selectedTx.isMarkedForDeletion {
|
||||
continue
|
||||
}
|
||||
tx := selectedTx.txDesc.Tx
|
||||
|
@ -1,22 +0,0 @@
|
||||
package mining
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/kaspanet/kaspad/util"
|
||||
)
|
||||
|
||||
type testTxDescDefinition struct {
|
||||
fee uint64
|
||||
mass uint64
|
||||
gas uint64
|
||||
|
||||
expectedMinSelectedTimes uint64
|
||||
expectedMaxSelectedTimes uint64
|
||||
|
||||
tx *util.Tx
|
||||
}
|
||||
|
||||
func (dd testTxDescDefinition) String() string {
|
||||
return fmt.Sprintf("[fee: %d, gas: %d, mass: %d]", dd.fee, dd.gas, dd.mass)
|
||||
}
|
@ -74,7 +74,3 @@ func (b *blockProgressLogger) LogBlockBlueScore(block *util.Block, blueScore uin
|
||||
b.receivedLogTx = 0
|
||||
b.lastBlockLogTime = now
|
||||
}
|
||||
|
||||
func (b *blockProgressLogger) SetLastLogTime(time time.Time) {
|
||||
b.lastBlockLogTime = time
|
||||
}
|
||||
|
@ -214,14 +214,13 @@ func (sm *SyncManager) startSync() {
|
||||
continue
|
||||
}
|
||||
|
||||
if time.Now().Sub(state.lastSelectedTipRequest) < minGetSelectedTipInterval {
|
||||
if time.Since(state.lastSelectedTipRequest) < minGetSelectedTipInterval {
|
||||
continue
|
||||
}
|
||||
|
||||
queueMsgGetSelectedTip(peer, state)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (sm *SyncManager) shouldQueryPeerSelectedTips() bool {
|
||||
|
10
peer/peer.go
10
peer/peer.go
@ -351,13 +351,6 @@ type StatsSnap struct {
|
||||
LastPingMicros int64
|
||||
}
|
||||
|
||||
// HashFunc is a function which returns a block hash, height and error
|
||||
// It is used as a callback to get newest block details.
|
||||
type HashFunc func() (hash *daghash.Hash, height int32, err error)
|
||||
|
||||
// AddrFunc is a func which takes an address and returns a related address.
|
||||
type AddrFunc func(remoteAddr *wire.NetAddress) *wire.NetAddress
|
||||
|
||||
// HostToNetAddrFunc is a func which takes a host, port, services and returns
|
||||
// the netaddress.
|
||||
type HostToNetAddrFunc func(host string, port uint16,
|
||||
@ -420,9 +413,6 @@ type Peer struct {
|
||||
prevGetBlockInvsMtx sync.Mutex
|
||||
prevGetBlockInvsLow *daghash.Hash
|
||||
prevGetBlockInvsHigh *daghash.Hash
|
||||
prevGetHdrsMtx sync.Mutex
|
||||
prevGetHdrsLow *daghash.Hash
|
||||
prevGetHdrsHigh *daghash.Hash
|
||||
|
||||
// These fields keep track of statistics for the peer and are protected
|
||||
// by the statsMtx mutex.
|
||||
|
@ -34,7 +34,7 @@ func (r FutureGetSelectedTipHashResult) Receive() (*daghash.Hash, error) {
|
||||
var txHashStr string
|
||||
err = json.Unmarshal(res, &txHashStr)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getSelectedTip response")
|
||||
}
|
||||
return daghash.NewHashFromStr(txHashStr)
|
||||
}
|
||||
@ -71,13 +71,13 @@ func (r FutureGetBlockResult) Receive() (*wire.MsgBlock, error) {
|
||||
var blockHex string
|
||||
err = json.Unmarshal(res, &blockHex)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getBlock response")
|
||||
}
|
||||
|
||||
// Decode the serialized block hex to raw bytes.
|
||||
serializedBlock, err := hex.DecodeString(blockHex)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode block hex")
|
||||
}
|
||||
|
||||
// Deserialize the block and return it.
|
||||
@ -126,7 +126,7 @@ func (r FutureGetBlocksResult) Receive() (*rpcmodel.GetBlocksResult, error) {
|
||||
|
||||
var result rpcmodel.GetBlocksResult
|
||||
if err := json.Unmarshal(res, &result); err != nil {
|
||||
return nil, errors.Wrapf(err, "%s", string(res))
|
||||
return nil, errors.Wrap(err, string(res))
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
@ -163,7 +163,7 @@ func (r FutureGetBlockVerboseResult) Receive() (*rpcmodel.GetBlockVerboseResult,
|
||||
var blockResult rpcmodel.GetBlockVerboseResult
|
||||
err = json.Unmarshal(res, &blockResult)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getBlock response")
|
||||
}
|
||||
return &blockResult, nil
|
||||
}
|
||||
@ -268,7 +268,7 @@ func (r FutureGetChainFromBlockResult) Receive() (*rpcmodel.GetChainFromBlockRes
|
||||
|
||||
var result rpcmodel.GetChainFromBlockResult
|
||||
if err := json.Unmarshal(res, &result); err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getChainFromBlock response")
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
@ -342,7 +342,7 @@ func (r FutureGetBlockDAGInfoResult) Receive() (*rpcmodel.GetBlockDAGInfoResult,
|
||||
|
||||
var dagInfo rpcmodel.GetBlockDAGInfoResult
|
||||
if err := json.Unmarshal(res, &dagInfo); err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getBlockDagInfo response")
|
||||
}
|
||||
return &dagInfo, nil
|
||||
}
|
||||
@ -401,12 +401,12 @@ func (r FutureGetBlockHeaderResult) Receive() (*wire.BlockHeader, error) {
|
||||
var bhHex string
|
||||
err = json.Unmarshal(res, &bhHex)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getBlockHeader response")
|
||||
}
|
||||
|
||||
serializedBH, err := hex.DecodeString(bhHex)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode block header hex")
|
||||
}
|
||||
|
||||
// Deserialize the blockheader and return it.
|
||||
@ -458,7 +458,7 @@ func (r FutureGetBlockHeaderVerboseResult) Receive() (*rpcmodel.GetBlockHeaderVe
|
||||
var bh rpcmodel.GetBlockHeaderVerboseResult
|
||||
err = json.Unmarshal(res, &bh)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getBlockHeader response")
|
||||
}
|
||||
|
||||
return &bh, nil
|
||||
@ -504,7 +504,7 @@ func (r FutureGetMempoolEntryResult) Receive() (*rpcmodel.GetMempoolEntryResult,
|
||||
var mempoolEntryResult rpcmodel.GetMempoolEntryResult
|
||||
err = json.Unmarshal(res, &mempoolEntryResult)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getMempoolEntry response")
|
||||
}
|
||||
|
||||
return &mempoolEntryResult, nil
|
||||
@ -542,7 +542,7 @@ func (r FutureGetRawMempoolResult) Receive() ([]*daghash.Hash, error) {
|
||||
var txHashStrs []string
|
||||
err = json.Unmarshal(res, &txHashStrs)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getRawMempool response")
|
||||
}
|
||||
|
||||
// Create a slice of ShaHash arrays from the string slice.
|
||||
@ -594,7 +594,7 @@ func (r FutureGetRawMempoolVerboseResult) Receive() (map[string]rpcmodel.GetRawM
|
||||
var mempoolItems map[string]rpcmodel.GetRawMempoolVerboseResult
|
||||
err = json.Unmarshal(res, &mempoolItems)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getRawMempool response")
|
||||
}
|
||||
return mempoolItems, nil
|
||||
}
|
||||
@ -634,7 +634,7 @@ func (r FutureGetSubnetworkResult) Receive() (*rpcmodel.GetSubnetworkResult, err
|
||||
var getSubnetworkResult *rpcmodel.GetSubnetworkResult
|
||||
err = json.Unmarshal(res, &getSubnetworkResult)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getSubnetwork response")
|
||||
}
|
||||
|
||||
return getSubnetworkResult, nil
|
||||
@ -677,7 +677,7 @@ func (r FutureGetTxOutResult) Receive() (*rpcmodel.GetTxOutResult, error) {
|
||||
var txOutInfo *rpcmodel.GetTxOutResult
|
||||
err = json.Unmarshal(res, &txOutInfo)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode getTxOut response")
|
||||
}
|
||||
|
||||
return txOutInfo, nil
|
||||
@ -719,7 +719,7 @@ func (r FutureRescanBlocksResult) Receive() ([]rpcmodel.RescannedBlock, error) {
|
||||
var rescanBlocksResult []rpcmodel.RescannedBlock
|
||||
err = json.Unmarshal(res, &rescanBlocksResult)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
return nil, errors.Wrap(err, "couldn't decode rescanBlocks response")
|
||||
}
|
||||
|
||||
return rescanBlocksResult, nil
|
||||
|
@ -866,8 +866,10 @@ func (c *Client) sendRequest(data *jsonRequestData) chan *response {
|
||||
})
|
||||
if cancelOnTimeout {
|
||||
spawn(func() {
|
||||
ticker := time.NewTicker(c.config.RequestTimeout)
|
||||
defer ticker.Stop()
|
||||
select {
|
||||
case <-time.Tick(c.config.RequestTimeout):
|
||||
case <-ticker.C:
|
||||
responseChan <- &response{err: errors.WithStack(ErrResponseTimedOut)}
|
||||
case resp := <-jReq.responseChan:
|
||||
responseChan <- resp
|
||||
@ -906,15 +908,6 @@ func (c *Client) sendCmd(cmd interface{}) chan *response {
|
||||
return c.sendRequest(jReqData)
|
||||
}
|
||||
|
||||
// sendCmdAndWait sends the passed command to the associated server, waits
|
||||
// for the reply, and returns the result from it. It will return the error
|
||||
// field in the reply if there is one.
|
||||
func (c *Client) sendCmdAndWait(cmd interface{}) (interface{}, error) {
|
||||
// Marshal the command to JSON-RPC, send it to the connected server, and
|
||||
// wait for a response on the returned channel.
|
||||
return receiveFuture(c.sendCmd(cmd))
|
||||
}
|
||||
|
||||
// Disconnected returns whether or not the server is disconnected. If a
|
||||
// websocket client was created but never connected, this also returns false.
|
||||
func (c *Client) Disconnected() bool {
|
||||
|
@ -531,15 +531,6 @@ func (c *Client) NotifyChainChanges() error {
|
||||
return c.NotifyChainChangesAsync().Receive()
|
||||
}
|
||||
|
||||
// newOutpointFromWire constructs the jsonrpc representation of a transaction
|
||||
// outpoint from the wire type.
|
||||
func newOutpointFromWire(op *wire.Outpoint) rpcmodel.Outpoint {
|
||||
return rpcmodel.Outpoint{
|
||||
TxID: op.TxID.String(),
|
||||
Index: op.Index,
|
||||
}
|
||||
}
|
||||
|
||||
// FutureNotifyNewTransactionsResult is a future promise to deliver the result
|
||||
// of a NotifyNewTransactionsAsync RPC invocation (or an applicable error).
|
||||
type FutureNotifyNewTransactionsResult chan *response
|
||||
|
@ -271,7 +271,7 @@ func resultTypeHelp(xT descLookupFunc, rt reflect.Type, fieldDescKey string) str
|
||||
w.Init(&formatted, 0, 4, 1, ' ', 0)
|
||||
for i, text := range results {
|
||||
if i == len(results)-1 {
|
||||
fmt.Fprintf(w, text)
|
||||
fmt.Fprint(w, text)
|
||||
} else {
|
||||
fmt.Fprintln(w, text)
|
||||
}
|
||||
|
@ -282,6 +282,6 @@ func RegisteredCmdMethods() []string {
|
||||
methods = append(methods, k)
|
||||
}
|
||||
|
||||
sort.Sort(sort.StringSlice(methods))
|
||||
sort.Strings(methods)
|
||||
return methods
|
||||
}
|
||||
|
@ -258,7 +258,7 @@ func TestRegisteredCmdMethods(t *testing.T) {
|
||||
// Ensure the returned methods are sorted.
|
||||
sortedMethods := make([]string, len(methods))
|
||||
copy(sortedMethods, methods)
|
||||
sort.Sort(sort.StringSlice(sortedMethods))
|
||||
sort.Strings(sortedMethods)
|
||||
if !reflect.DeepEqual(sortedMethods, methods) {
|
||||
t.Fatal("RegisteredCmdMethods: methods are not sorted")
|
||||
}
|
||||
|
@ -117,18 +117,6 @@ type outboundPeerConnectedMsg struct {
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
// updatePeerHeightsMsg is a message sent from the blockmanager to the server
|
||||
// after a new block has been accepted. The purpose of the message is to update
|
||||
// the heights of peers that were known to announce the block before we
|
||||
// connected it to the DAG or recognized it as an orphan. With these
|
||||
// updates, peer heights will be kept up to date, allowing for fresh data when
|
||||
// selecting sync peer candidacy.
|
||||
type updatePeerHeightsMsg struct {
|
||||
newHash *daghash.Hash
|
||||
newHeight int32
|
||||
originPeer *peer.Peer
|
||||
}
|
||||
|
||||
// Peer extends the peer to maintain state shared by the server and
|
||||
// the blockmanager.
|
||||
type Peer struct {
|
||||
@ -224,13 +212,6 @@ func (ps *peerState) forAllPeers(callback func(sp *Peer) bool) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// cfHeaderKV is a tuple of a filter header and its associated block hash. The
|
||||
// struct is used to cache cfcheckpt responses.
|
||||
type cfHeaderKV struct {
|
||||
blockHash *daghash.Hash
|
||||
filterHeader *daghash.Hash
|
||||
}
|
||||
|
||||
// Server provides a kaspa server for handling communications to and from
|
||||
// kaspa peers.
|
||||
type Server struct {
|
||||
@ -238,7 +219,6 @@ type Server struct {
|
||||
// Putting the uint64s first makes them 64-bit aligned for 32-bit systems.
|
||||
bytesReceived uint64 // Total bytes received from all peers since start.
|
||||
bytesSent uint64 // Total bytes sent by all peers since start.
|
||||
started int32
|
||||
shutdown int32
|
||||
shutdownSched int32
|
||||
|
||||
@ -279,7 +259,6 @@ type Server struct {
|
||||
AcceptanceIndex *indexers.AcceptanceIndex
|
||||
|
||||
notifyNewTransactions func(txns []*mempool.TxDesc)
|
||||
isRPCServerActive bool
|
||||
}
|
||||
|
||||
// newServerPeer returns a new serverPeer instance. The peer needs to be set by
|
||||
@ -877,10 +856,7 @@ func (s *Server) handleQuery(state *peerState, querymsg interface{}) {
|
||||
shouldMineOnGenesis := true
|
||||
if state.Count() != 0 {
|
||||
shouldMineOnGenesis = state.forAllPeers(func(sp *Peer) bool {
|
||||
if !sp.SelectedTipHash().IsEqual(s.DAGParams.GenesisHash) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
return sp.SelectedTipHash().IsEqual(s.DAGParams.GenesisHash)
|
||||
})
|
||||
} else {
|
||||
shouldMineOnGenesis = false
|
||||
@ -1316,9 +1292,7 @@ out:
|
||||
// When an InvVect has been added to a block, we can
|
||||
// now remove it, if it was present.
|
||||
case broadcastInventoryDel:
|
||||
if _, ok := pendingInvs[*msg]; ok {
|
||||
delete(pendingInvs, *msg)
|
||||
}
|
||||
delete(pendingInvs, *msg)
|
||||
}
|
||||
|
||||
case <-timer.C:
|
||||
|
@ -12,15 +12,6 @@ import (
|
||||
func handleCreateRawTransaction(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
|
||||
c := cmd.(*rpcmodel.CreateRawTransactionCmd)
|
||||
|
||||
// Validate the locktime, if given.
|
||||
if c.LockTime != nil &&
|
||||
(*c.LockTime < 0 || *c.LockTime > wire.MaxTxInSequenceNum) {
|
||||
return nil, &rpcmodel.RPCError{
|
||||
Code: rpcmodel.ErrRPCInvalidParameter,
|
||||
Message: "Locktime out of range",
|
||||
}
|
||||
}
|
||||
|
||||
txIns := []*wire.TxIn{}
|
||||
// Add all transaction inputs to a new transaction after performing
|
||||
// some validity checks.
|
||||
|
@ -14,7 +14,7 @@ func handleNotifyNewTransactions(wsc *wsClient, icmd interface{}) (interface{},
|
||||
}
|
||||
|
||||
isVerbose := cmd.Verbose != nil && *cmd.Verbose
|
||||
if isVerbose == false && cmd.Subnetwork != nil {
|
||||
if !isVerbose && cmd.Subnetwork != nil {
|
||||
return nil, &rpcmodel.RPCError{
|
||||
Code: rpcmodel.ErrRPCInvalidParameter,
|
||||
Message: "Subnetwork switch is only allowed if verbose=true",
|
||||
|
@ -743,7 +743,7 @@ func (c *helpCacher) rpcUsage(includeWebsockets bool) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sort.StringSlice(usageTexts))
|
||||
sort.Strings(usageTexts)
|
||||
c.usage = strings.Join(usageTexts, "\n")
|
||||
return c.usage, nil
|
||||
}
|
||||
|
@ -345,36 +345,6 @@ func (f *wsClientFilter) existsAddress(a util.Address) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// removeAddress removes the passed address, if it exists, from the
|
||||
// wsClientFilter.
|
||||
//
|
||||
// NOTE: This extension was ported from github.com/decred/dcrd
|
||||
func (f *wsClientFilter) removeAddress(a util.Address) {
|
||||
switch a := a.(type) {
|
||||
case *util.AddressPubKeyHash:
|
||||
delete(f.pubKeyHashes, *a.Hash160())
|
||||
return
|
||||
case *util.AddressScriptHash:
|
||||
delete(f.scriptHashes, *a.Hash160())
|
||||
return
|
||||
}
|
||||
|
||||
delete(f.otherAddresses, a.EncodeAddress())
|
||||
}
|
||||
|
||||
// removeAddressStr parses an address from a string and then removes it from the
|
||||
// wsClientFilter using removeAddress.
|
||||
//
|
||||
// NOTE: This extension was ported from github.com/decred/dcrd
|
||||
func (f *wsClientFilter) removeAddressStr(s string, params *dagconfig.Params) {
|
||||
a, err := util.DecodeAddress(s, params.Prefix)
|
||||
if err == nil {
|
||||
f.removeAddress(a)
|
||||
} else {
|
||||
delete(f.otherAddresses, s)
|
||||
}
|
||||
}
|
||||
|
||||
// addUnspentOutpoint adds an outpoint to the wsClientFilter.
|
||||
//
|
||||
// NOTE: This extension was ported from github.com/decred/dcrd
|
||||
@ -391,14 +361,6 @@ func (f *wsClientFilter) existsUnspentOutpoint(op *wire.Outpoint) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// removeUnspentOutpoint removes the passed outpoint, if it exists, from the
|
||||
// wsClientFilter.
|
||||
//
|
||||
// NOTE: This extension was ported from github.com/decred/dcrd
|
||||
func (f *wsClientFilter) removeUnspentOutpoint(op *wire.Outpoint) {
|
||||
delete(f.unspent, *op)
|
||||
}
|
||||
|
||||
// Notification types
|
||||
type notificationBlockAdded util.Block
|
||||
type notificationChainChanged struct {
|
||||
@ -760,11 +722,7 @@ func (m *wsNotificationManager) notifyForNewTx(clients map[chan struct{}]*wsClie
|
||||
|
||||
// Third, build again, now with the modified mtx, for a Partial version
|
||||
marshalledJSONVerbosePartial, ok = build()
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
return ok
|
||||
}
|
||||
|
||||
for _, wsc := range clients {
|
||||
|
@ -4,33 +4,12 @@ import (
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/kaspanet/kaspad/config"
|
||||
"github.com/kaspanet/kaspad/connmgr"
|
||||
"github.com/kaspanet/kaspad/peer"
|
||||
"github.com/kaspanet/kaspad/util"
|
||||
)
|
||||
|
||||
// Peer extends the peer to maintain state shared by the server and
|
||||
// the blockmanager.
|
||||
type Peer struct {
|
||||
*peer.Peer
|
||||
|
||||
// The following variables must only be used atomically
|
||||
FeeFilter int64
|
||||
|
||||
relayMtx sync.Mutex
|
||||
DynamicBanScore connmgr.DynamicBanScore
|
||||
quit chan struct{}
|
||||
DisableRelayTx bool
|
||||
|
||||
// The following chans are used to sync blockmanager and server.
|
||||
txProcessed chan struct{}
|
||||
blockProcessed chan struct{}
|
||||
}
|
||||
|
||||
// KaspadLookup resolves the IP of the given host using the correct DNS lookup
|
||||
// function depending on the configuration options.
|
||||
func KaspadLookup(host string) ([]net.IP, error) {
|
||||
|
@ -7,9 +7,6 @@ package txscript
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kaspanet/kaspad/logger"
|
||||
"math/big"
|
||||
|
||||
"github.com/kaspanet/kaspad/ecc"
|
||||
"github.com/kaspanet/kaspad/wire"
|
||||
)
|
||||
|
||||
@ -39,9 +36,6 @@ const (
|
||||
MaxScriptSize = 10000
|
||||
)
|
||||
|
||||
// halforder is used to tame ECDSA malleability (see BIP0062).
|
||||
var halfOrder = new(big.Int).Rsh(ecc.S256().N, 1)
|
||||
|
||||
// Engine is the virtual machine that executes scripts.
|
||||
type Engine struct {
|
||||
scripts [][]parsedOpcode
|
||||
@ -117,7 +111,7 @@ func (vm *Engine) executeOpcode(pop *parsedOpcode) error {
|
||||
// Ensure all executed data push opcodes use the minimal encoding when
|
||||
// the minimal data verification flag is set.
|
||||
if vm.isBranchExecuting() &&
|
||||
pop.opcode.value >= 0 && pop.opcode.value <= OpPushData4 {
|
||||
pop.opcode.value != 0 && pop.opcode.value <= OpPushData4 {
|
||||
|
||||
if err := pop.checkMinimalDataPush(); err != nil {
|
||||
return err
|
||||
|
@ -365,15 +365,3 @@ func TestScripts(t *testing.T) {
|
||||
testScripts(t, tests, true)
|
||||
testScripts(t, tests, false)
|
||||
}
|
||||
|
||||
// testVecF64ToUint32 properly handles conversion of float64s read from the JSON
|
||||
// test data to unsigned 32-bit integers. This is necessary because some of the
|
||||
// test data uses -1 as a shortcut to mean max uint32 and direct conversion of a
|
||||
// negative float to an unsigned int is implementation dependent and therefore
|
||||
// doesn't result in the expected value on all platforms. This function woks
|
||||
// around that limitation by converting to a 32-bit signed integer first and
|
||||
// then to a 32-bit unsigned integer which results in the expected behavior on
|
||||
// all platforms.
|
||||
func testVecF64ToUint32(f float64) uint32 {
|
||||
return uint32(int32(f))
|
||||
}
|
||||
|
@ -74,7 +74,7 @@ func (s *SigCache) Add(sigHash daghash.Hash, sig *ecc.Signature, pubKey *ecc.Pub
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if s.maxEntries <= 0 {
|
||||
if s.maxEntries == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -432,7 +432,7 @@ func TestSignTxOutput(t *testing.T) {
|
||||
break
|
||||
}
|
||||
|
||||
sigScript, err := SignTxOutput(&dagconfig.TestnetParams,
|
||||
_, err = SignTxOutput(&dagconfig.TestnetParams,
|
||||
tx, i, scriptScriptPubKey, hashType,
|
||||
mkGetKey(map[string]addressToKey{
|
||||
address.EncodeAddress(): {key, false},
|
||||
@ -447,7 +447,7 @@ func TestSignTxOutput(t *testing.T) {
|
||||
|
||||
// by the above loop, this should be valid, now sign
|
||||
// again and merge.
|
||||
sigScript, err = SignTxOutput(&dagconfig.TestnetParams,
|
||||
sigScript, err := SignTxOutput(&dagconfig.TestnetParams,
|
||||
tx, i, scriptScriptPubKey, hashType,
|
||||
mkGetKey(map[string]addressToKey{
|
||||
address.EncodeAddress(): {key, false},
|
||||
@ -569,7 +569,7 @@ func TestSignTxOutput(t *testing.T) {
|
||||
break
|
||||
}
|
||||
|
||||
sigScript, err := SignTxOutput(&dagconfig.TestnetParams,
|
||||
_, err = SignTxOutput(&dagconfig.TestnetParams,
|
||||
tx, i, scriptScriptPubKey, hashType,
|
||||
mkGetKey(map[string]addressToKey{
|
||||
address.EncodeAddress(): {key, true},
|
||||
@ -584,7 +584,7 @@ func TestSignTxOutput(t *testing.T) {
|
||||
|
||||
// by the above loop, this should be valid, now sign
|
||||
// again and merge.
|
||||
sigScript, err = SignTxOutput(&dagconfig.TestnetParams,
|
||||
sigScript, err := SignTxOutput(&dagconfig.TestnetParams,
|
||||
tx, i, scriptScriptPubKey, hashType,
|
||||
mkGetKey(map[string]addressToKey{
|
||||
address.EncodeAddress(): {key, true},
|
||||
@ -633,14 +633,6 @@ var (
|
||||
0xb4, 0xfc, 0x4e, 0x55, 0xd4, 0x88, 0x42, 0xb3, 0xa1, 0x65,
|
||||
0xac, 0x70, 0x7f, 0x3d, 0xa4, 0x39, 0x5e, 0xcb, 0x3b, 0xb0,
|
||||
0xd6, 0x0e, 0x06, 0x92}
|
||||
pubkeyX = []byte{0xb2, 0x52, 0xf0, 0x49, 0x85, 0x78, 0x03, 0x03, 0xc8,
|
||||
0x7d, 0xce, 0x51, 0x7f, 0xa8, 0x69, 0x0b, 0x91, 0x95, 0xf4,
|
||||
0xf3, 0x5c, 0x26, 0x73, 0x05, 0x05, 0xa2, 0xee, 0xbc, 0x09,
|
||||
0x38, 0x34, 0x3a}
|
||||
pubkeyY = []byte{0xb7, 0xc6, 0x7d, 0xb2, 0xe1, 0xff, 0xc8, 0x43, 0x1f,
|
||||
0x63, 0x32, 0x62, 0xaa, 0x60, 0xc6, 0x83, 0x30, 0xbd, 0x24,
|
||||
0x7e, 0xef, 0xdb, 0x6f, 0x2e, 0x8d, 0x56, 0xf0, 0x3c, 0x9f,
|
||||
0x6d, 0xb6, 0xf8}
|
||||
uncompressedScriptPubKey = []byte{0x76, 0xa9, 0x14, 0xd1, 0x7c, 0xb5,
|
||||
0xeb, 0xa4, 0x02, 0xcb, 0x68, 0xe0, 0x69, 0x56, 0xbf, 0x32,
|
||||
0x53, 0x90, 0x0e, 0x0a, 0x86, 0xc9, 0xfa, 0x88, 0xac}
|
||||
@ -650,8 +642,6 @@ var (
|
||||
shortScriptPubKey = []byte{0x76, 0xa9, 0x14, 0xd1, 0x7c, 0xb5,
|
||||
0xeb, 0xa4, 0x02, 0xcb, 0x68, 0xe0, 0x69, 0x56, 0xbf, 0x32,
|
||||
0x53, 0x90, 0x0e, 0x0a, 0x88, 0xac}
|
||||
uncompressedAddrStr = "1L6fd93zGmtzkK6CsZFVVoCwzZV3MUtJ4F"
|
||||
compressedAddrStr = "14apLppt9zTq6cNw8SDfiJhk9PhkZrQtYZ"
|
||||
)
|
||||
|
||||
// Pretend output amounts.
|
||||
|
@ -196,13 +196,6 @@ func payToScriptHashScript(scriptHash []byte) ([]byte, error) {
|
||||
AddOp(OpEqual).Script()
|
||||
}
|
||||
|
||||
// payToPubkeyScript creates a new script to pay a transaction output to a
|
||||
// public key. It is expected that the input is a valid pubkey.
|
||||
func payToPubKeyScript(serializedPubKey []byte) ([]byte, error) {
|
||||
return NewScriptBuilder().AddData(serializedPubKey).
|
||||
AddOp(OpCheckSig).Script()
|
||||
}
|
||||
|
||||
// PayToAddrScript creates a new script to pay a transaction output to a the
|
||||
// specified address.
|
||||
func PayToAddrScript(addr util.Address) ([]byte, error) {
|
||||
|
@ -136,10 +136,8 @@ func TestExtractScriptPubKeyAddrs(t *testing.T) {
|
||||
|
||||
t.Logf("Running %d tests.", len(tests))
|
||||
for i, test := range tests {
|
||||
class, addr, err := ExtractScriptPubKeyAddress(
|
||||
class, addr, _ := ExtractScriptPubKeyAddress(
|
||||
test.script, &dagconfig.MainnetParams)
|
||||
if err != nil {
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(addr, test.addr) {
|
||||
t.Errorf("ExtractScriptPubKeyAddress #%d (%s) unexpected "+
|
||||
|
@ -60,7 +60,7 @@ func NewTLSCertPair(organization string, validUntil time.Time, extraHosts []stri
|
||||
|
||||
addIP := func(ipAddr net.IP) {
|
||||
for _, ip := range ipAddresses {
|
||||
if bytes.Equal(ip, ipAddr) {
|
||||
if ip.Equal(ipAddr) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
@ -191,7 +191,7 @@ func Decode(dst *Hash, src string) error {
|
||||
var reversedHash Hash
|
||||
_, err := hex.Decode(reversedHash[HashSize-hex.DecodedLen(len(srcBytes)):], srcBytes)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
return errors.Wrap(err, "couldn't decode hash hex")
|
||||
}
|
||||
|
||||
// Reverse copy from the temporary hash to destination. Because the
|
||||
|
@ -55,6 +55,9 @@ func TestTx(t *testing.T) {
|
||||
// ID for block 100,000 transaction 1.
|
||||
wantIDStr := "011f7009d8e5a99c4cf2f7216a3eb6044a7017a98732a8fb6390fbbb668e84d8"
|
||||
wantID, err := daghash.NewTxIDFromStr(wantIDStr)
|
||||
if err != nil {
|
||||
t.Errorf("NewTxIDFromStr: %s", err)
|
||||
}
|
||||
// Request the ID multiple times to test generation and caching.
|
||||
for i := 0; i < 2; i++ {
|
||||
id := secondTx.ID()
|
||||
|
@ -530,6 +530,10 @@ func (msg *MsgTx) KaspaDecode(r io.Reader, pver uint32) error {
|
||||
|
||||
msg.Payload = make([]byte, payloadLength)
|
||||
_, err = io.ReadFull(r, msg.Payload)
|
||||
if err != nil {
|
||||
returnScriptBuffers()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Create a single allocation to house all of the scripts and set each
|
||||
|
Loading…
x
Reference in New Issue
Block a user