netnode

package
v0.0.0-...-0594d8f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2025 License: MIT Imports: 25 Imported by: 1

Documentation

Index

Constants

View Source
const (
	THRESHOLD_A    = "0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
	THRESHOLD_B    = "00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
	THRESHOLD_C    = "000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
	THRESHOLD_POOL = "1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
)
View Source
const ALPHA_FACTOR = 4
View Source
const BACKUP_DIR = "backup"
View Source
const BACKUP_FREQUENCY = 2 * 60 * 60 // every 2 hours
View Source
const BLOCK_SPEED_AVERAGE_WINDOW = 150
View Source
const BROOMBASE_DEFAULT_DIR = "broombase"
View Source
const CHANNEL_BUFFER_SIZE = 10
View Source
const COINBASE = "coinbase"
View Source
const COINBASE_VESTING_BLOCK_NUMBER = 10 // coinbase txns don't go out until a fork is hopefully resolved, these txn amounts are not spendable for this number of blocks
View Source
const DEFAULT_MINING_THRESHOLD = "0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
View Source
const EXECUTOR_WORKER_COUNT = 4
View Source
const EXPOSED_PORT = "80"
View Source
const GENESIS = "genesis"
View Source
const GENESIS_BLOCK_HEIGHT = 0
View Source
const LEDGER_DEFAULT_DIR = "ledger"
View Source
const MAX_BLOCK_SIZE = 1000
View Source
const MAX_PEER_CONNECTIONS = 200
View Source
const MINING_PAYOUT_LOOKBACK = 10

we want to resolve mining payout faster than our won blocks vest

View Source
const MINING_POOL_GOB = "mining_pool.gob"
View Source
const NO_PEERS_ERROR = "no peers found"
View Source
const PEER_CONNECTION_RETRIES = 5
View Source
const PEER_SAMPLE_SIZE = 30
View Source
const PROOF_LIMITER_RATE = time.Millisecond * 300
View Source
const PROTOCOL_MAX_SIZE = 30_000_000
View Source
const RETRY_TIME = 3 // in seconds
View Source
const STARTING_PAYOUT = 10_000
View Source
const SYNC_CHECK_DURATION = 2 * time.Minute
View Source
const TARGET_BLOCK_TIME = 60
View Source
const TCP_PORT = "4188"

Variables

View Source
var GENESIS_HASH = "fd1cb7926a4447454a00a3c5c75126ad8ec053bc5ba61d706ca687428c8af5ac"
View Source
var GENESIS_TXN = Transaction{
	Coinbase: false,
	To:       "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEW7I9+SUHOW28jjABqnpO76tqwG/nCG/jMMPuUfIQryMPlCdxPwUrSP49ioqYZAf2kXrXQ7MQE891OXBTSpvlsA==",
	Note:     "Matthew 5:16",
	Amount:   STARTING_PAYOUT,
}
View Source
var START_DELIMETER = []byte{0x01, 0x14}

Functions

func CheckKeys

func CheckKeys(pub, priv string)

func CompareHash

func CompareHash(hash, target string) bool

func ValidateNonce

func ValidateNonce(txns []Transaction, lastNonce int64) (curentNonce int64, err error)

first txn nonce must be 1

func ValidateTransactionGroup

func ValidateTransactionGroup(currentBalance int64, currentNonce int64, txns []Transaction) error

other block txns are needed to validate the current txn The current "txn to validate" can be added to the list of the rest of the txns,

Types

type Block

type Block struct {
	Hash string `json:"hash"`

	Timestamp         int64           `json:"timestamp"`
	Height            int64           `json:"height"`
	Nonce             int64           `json:"nonce"`
	PreviousBlockHash string          `json:"previous"`
	Transactions      TransactionPool `json:"transactions"`
}

func NewBlock

func NewBlock(myAddress string, note string, PreviousBlockHash string, height int64, currentReward int64) *Block

func (*Block) CalculateHash

func (b *Block) CalculateHash() string

func (Block) DeepCopy

func (b Block) DeepCopy() Block

func (*Block) GetTimestampTime

func (b *Block) GetTimestampTime() time.Time

func (*Block) MineWithWorkers

func (b *Block) MineWithWorkers(ctx context.Context, target string, workers int, solutionChan chan Block, done chan struct{}, solutionOperators map[string]func(b Block))

func (*Block) RandomizeNonce

func (b *Block) RandomizeNonce()

func (*Block) RotateMiningValues

func (b *Block) RotateMiningValues() (hash string)

func (*Block) Serialize

func (b *Block) Serialize() []byte

func (*Block) SetStampNow

func (b *Block) SetStampNow()

func (*Block) SignHash

func (b *Block) SignHash()

func (Block) StartSolutionWorker

func (b Block) StartSolutionWorker(ctx context.Context, target string, solutionChan chan Block, done chan struct{}, solutionOperators map[string]func(b Block))

func (*Block) ValidateHash

func (b *Block) ValidateHash() bool

type BlockTimeDifficulty

type BlockTimeDifficulty struct {
	Height     int64     `json:"height"`
	Time       time.Time `json:"time"`
	Difficulty string    `json:"difficulty"`
}

type BottleNeckQueue

type BottleNeckQueue[T any] struct {
	// contains filtered or unexported fields
}

func NewBottleNeckQueue

func NewBottleNeckQueue[T any]() *BottleNeckQueue[T]

func (*BottleNeckQueue[T]) Add

func (bn *BottleNeckQueue[T]) Add(value T)

func (*BottleNeckQueue[T]) Clear

func (bn *BottleNeckQueue[T]) Clear()

func (*BottleNeckQueue[T]) HasNext

func (bn *BottleNeckQueue[T]) HasNext() bool

func (*BottleNeckQueue[T]) Pop

func (bn *BottleNeckQueue[T]) Pop() (value T, found bool)

type Broombase

type Broombase struct {
	Ledger *Ledger
	// contains filtered or unexported fields
}

func InitBroombaseWithDir

func InitBroombaseWithDir(dir, ledgerDir string) *Broombase

func NewBroombase

func NewBroombase() *Broombase

dir can be empty string

func (*Broombase) AddAndSync

func (bb *Broombase) AddAndSync(block *Block) error

DOES NOT USE SNAPSHOTS ONLY USED ON GENESIS

func (*Broombase) GetBlock

func (bb *Broombase) GetBlock(hash string, height int64) (block Block, found bool)

files are stored as height_hash.broom

func (*Broombase) GetFirstBlockByHeight

func (bb *Broombase) GetFirstBlockByHeight(height int) (string, bool)

used for testing only and copied by TempStorage

func (*Broombase) GetHighestBlock

func (bb *Broombase) GetHighestBlock() (height int64, hash string, err error)

reconciles forks, does not TRACK them

func (*Broombase) GetLedgerAt

func (bb *Broombase) GetLedgerAt(hash string, height int64) (*Ledger, bool)

func (*Broombase) ReceiveBlock

func (bb *Broombase) ReceiveBlock(block Block) error

not ledger safe,

func (*Broombase) StoreBlock

func (bb *Broombase) StoreBlock(block Block) error

func (*Broombase) StoreGivenLedger

func (bb *Broombase) StoreGivenLedger(ledger *Ledger) error

func (*Broombase) StoreLedger

func (bb *Broombase) StoreLedger(hash string, height int64) error

func (*Broombase) SyncLedger

func (bb *Broombase) SyncLedger(blockHeight int64, blockHash string) error

TDO: implement snapshots where we can jump to pick like n blocks ago

func (*Broombase) ValidateBlockHeaders

func (bb *Broombase) ValidateBlockHeaders(block *Block) error

type Executor

type Executor struct {
	Node     *Node
	Database *Broombase

	MsgChan chan []byte

	BlockChan        chan Block
	TxnChan          chan Transaction
	Mempool          map[string]Transaction
	MiningBlock      *Block
	MiningBlockMutex *sync.RWMutex

	EgressBlockChan chan Block
	EgressTxnChan   chan Transaction

	Port string

	// Mining Pool Config
	MiningPoolEnabled bool
	PoolTaxPercent    int64 // ex: 8 = %8
	PoolNote          string
	PrivateKey        string
	Pool              *MiningPool

	SolutionTargetOperators map[string]func(b Block)

	ProofLimiter *Limiter[WorkProof]
	// contains filtered or unexported fields
}

func NewExecutor

func NewExecutor(myAddress string, miningNote string, dir string, ledgerDir string, version string) *Executor

func (*Executor) AtomicCopyMiningBlock

func (ex *Executor) AtomicCopyMiningBlock() Block

func (*Executor) BackupFromFile

func (ex *Executor) BackupFromFile(filename string)

func (*Executor) Cancel

func (ex *Executor) Cancel()

func (*Executor) DownloadBackupFileFromPeer

func (ex *Executor) DownloadBackupFileFromPeer(peerAddress string)

func (*Executor) EnableMiningPool

func (ex *Executor) EnableMiningPool(tax int64, privateKey string, poolNote string)

call this from the cli before running the node

func (*Executor) GetAddressTransactions

func (ex *Executor) GetAddressTransactions(address string) []Transaction

func (*Executor) GetNodeNonce

func (ex *Executor) GetNodeNonce(address string) int64

func (*Executor) Mine

func (ex *Executor) Mine(ctx context.Context, solutionChan chan Block, doneChan chan struct{}, workers int)

func (*Executor) NetworkSync

func (ex *Executor) NetworkSync(ctx context.Context)

func (*Executor) NetworkSyncWithTracker

func (ex *Executor) NetworkSyncWithTracker(ctx context.Context) (syncRequired bool)

func (*Executor) PayoutMiners

func (ex *Executor) PayoutMiners(block Block)

func (*Executor) RunBackup

func (ex *Executor) RunBackup() error

func (*Executor) RunMiningLoop

func (ex *Executor) RunMiningLoop(ctx context.Context, workers int)

func (*Executor) RunNetworkSync

func (ex *Executor) RunNetworkSync(ctx context.Context) (caughtUp bool)

func (*Executor) SetPort

func (ex *Executor) SetPort(port string)

func (*Executor) SetupHttpServer

func (ex *Executor) SetupHttpServer()

func (*Executor) Start

func (ex *Executor) Start(workers int, self string, seeds ...string)

func (*Executor) ValidateIncomingPoolBlock

func (ex *Executor) ValidateIncomingPoolBlock(block Block) error

func (*Executor) ValidateIncomingPoolBlockNoHash

func (ex *Executor) ValidateIncomingPoolBlockNoHash(block Block) error

type Funnel

type Funnel[T any] struct {
	Ingress  chan T
	Egress   chan T
	FlowRate time.Duration
	// contains filtered or unexported fields
}

func NewFunnel

func NewFunnel[T any](rate time.Duration) *Funnel[T]

type HashHeight

type HashHeight struct {
	Height int    `json:"height"`
	Hash   string `json:"hash"`
}

type Ledger

type Ledger struct {
	Mut                 *sync.RWMutex         `json:"-"`
	MiningThresholdHash string                `json:"miningThreshold"`
	BlockHeight         int64                 `json:"blockHeight"`
	BlockHash           string                `json:"blockHash"`
	Balances            map[string]int64      `json:"balances"` // track receiver balances
	Nonces              map[string]int64      `json:"nonces"`   // track sender nonce values of transactions
	BlockTimeDifficulty []BlockTimeDifficulty `json:"blockTime"`
	Pending             []PendingBalance      `json:"pending"`
}

func (*Ledger) Accumulate

func (l *Ledger) Accumulate(b Block)

need to remove validity checking, assumes we have a valid block

func (*Ledger) CalculateCurrentReward

func (l *Ledger) CalculateCurrentReward() int

func (*Ledger) CheckLedger

func (l *Ledger) CheckLedger(address string) (found bool, nonce int64, balance int64)

func (*Ledger) Clear

func (l *Ledger) Clear()

func (*Ledger) GetAddressBalance

func (l *Ledger) GetAddressBalance(address string) (int64, bool)

func (*Ledger) GetAddressNonce

func (l *Ledger) GetAddressNonce(address string) (int64, bool)

func (*Ledger) GetCurrentMiningThreshold

func (l *Ledger) GetCurrentMiningThreshold() string

func (*Ledger) SyncNextBlock

func (l *Ledger) SyncNextBlock(validatedBlock Block)

Pass in a previously validated block, use l.ValidateBlock() CurrentLedger

func (*Ledger) ValidateBlock

func (l *Ledger) ValidateBlock(block Block) error

block must validate against current ledger TODO: Validate Mining difficulty

func (*Ledger) ValidateCoinbaseTxn

func (l *Ledger) ValidateCoinbaseTxn(coinbaseTxn Transaction, currentBlock int64) error

Add halving rule, or gambling rules

type Limiter

type Limiter[T any] struct {
	Fun       *Funnel[T]
	Publisher func(T)
	Validator func(T) bool
}

func NewLimiter

func NewLimiter[T any](rate time.Duration, publisher func(T), validator func(T) bool) *Limiter[T]

func (Limiter[T]) Publish

func (li Limiter[T]) Publish(value T)

type Message

type Message struct {
	Action MessageType `json:"action"`

	HostNames []string `json:"hostnames"`

	Block Block `json:"block"`

	Txn Transaction `json:"txn"`
}

type MessageType

type MessageType string
const (
	Ping          MessageType = "Ping"
	PeerBroadcast MessageType = "PeerBroadcast"
	TxnMsg        MessageType = "TxnMsg"
	BlockMsg      MessageType = "BlockMsg"
)

type MiningPool

type MiningPool struct {
	TaxPercent     int64
	BlockPayout    int64
	NodeAddress    string
	NodePrivateKey string
	TxnChan        chan Transaction
	WorkLog        map[int64]WorkTrie

	GetCurrentNonce func(address string) int64

	PoolNote string

	ListenerChan chan WorkProof
}

stores proof groups for specific heights

func InitMiningPool

func InitMiningPool(
	taxPercent int64,
	blockPayout int64,
	nodeMiningAddress string,
	txnChan chan Transaction,
	poolNote string,
	privateKey string,
	getNonce func(address string) int64,
) *MiningPool

func (*MiningPool) BackupWorkLog

func (mp *MiningPool) BackupWorkLog() error

func (*MiningPool) ClearBlock

func (mp *MiningPool) ClearBlock(i int64)

func (*MiningPool) LoadBackup

func (mp *MiningPool) LoadBackup() error

func (*MiningPool) PayoutBlock

func (mp *MiningPool) PayoutBlock(i int64)

func (*MiningPool) PublishWorkProof

func (mp *MiningPool) PublishWorkProof(wp WorkProof)

func (*MiningPool) Send

func (mp *MiningPool) Send(amount int64, address string, nonce int64)

func (*MiningPool) StartListener

func (mp *MiningPool) StartListener()

type Node

type Node struct {
	// contains filtered or unexported fields
}

func ActivateNode

func ActivateNode(msgChannel chan []byte, ingressBlock, egressBlock chan Block, ingressTxn, egressTxn chan Transaction, self string, seedNodes ...string) *Node

func (*Node) BalancePeers

func (n *Node) BalancePeers(hostNames []string)

func (*Node) DialPeer

func (n *Node) DialPeer(address string) (*Peer, error)

func (*Node) DropRandomPeer

func (n *Node) DropRandomPeer() bool

func (*Node) GetAddressSample

func (n *Node) GetAddressSample() []string

func (*Node) GossipPeers

func (n *Node) GossipPeers()

func (*Node) RacePeersForValidBlock

func (n *Node) RacePeersForValidBlock(hash string, height int) (Block, error)

func (*Node) RunEgress

func (n *Node) RunEgress()

func (*Node) SamplePeersBlock

func (n *Node) SamplePeersBlock(path string, height int, hash string) (consensus Block, err error)

func (*Node) SamplePeersHighestBlock

func (n *Node) SamplePeersHighestBlock() (hash string, height int, err error)

func (*Node) Schedule

func (n *Node) Schedule(task func(), period time.Duration)

func (*Node) ScheduleUnbanPeer

func (n *Node) ScheduleUnbanPeer(peer string)

func (*Node) Seed

func (n *Node) Seed()

func (*Node) StartListenIncomingMessages

func (n *Node) StartListenIncomingMessages()

type Peer

type Peer struct {
	// contains filtered or unexported fields
}

func (*Peer) ListenProtocol

func (p *Peer) ListenProtocol(msgChannel chan []byte)

type PendingBalance

type PendingBalance struct {
	To          string `json:"to"`
	Amount      int64  `json:"amount"`
	UnlockLevel int64  `json:"unlockLevel"`
}

type QueueNode

type QueueNode[T any] struct {
	// contains filtered or unexported fields
}

func NewRootQueueNode

func NewRootQueueNode[T any]() *QueueNode[T]

type RequestPeer

type RequestPeer struct {
	// contains filtered or unexported fields
}

func (*RequestPeer) SendMsg

func (r *RequestPeer) SendMsg(msg []byte) error

type TempStorage

type TempStorage struct {
	// contains filtered or unexported fields
}

func NewTempStorage

func NewTempStorage(dir string) *TempStorage

func (*TempStorage) DeleteBlock

func (ts *TempStorage) DeleteBlock(hash string, height int64) error

func (*TempStorage) GetBlock

func (ts *TempStorage) GetBlock(hash string, height int64) (Block, bool)

func (*TempStorage) GetFirstBlockByHeight

func (ts *TempStorage) GetFirstBlockByHeight(height int) (string, bool)

func (*TempStorage) StoreBlock

func (ts *TempStorage) StoreBlock(block Block) error

type Transaction

type Transaction struct {
	Sig string `json:"sig"`

	Coinbase bool   `json:"coinbase"`
	Note     string `json:"note"`
	Nonce    int64  `json:"nonce"`
	To       string `json:"to"`
	From     string `json:"from"`
	Amount   int64  `json:"amount"`
}

func (*Transaction) Serialize

func (t *Transaction) Serialize() []byte

func (*Transaction) Sign

func (t *Transaction) Sign(privateKey string) error

func (*Transaction) ValidateSig

func (t *Transaction) ValidateSig() (bool, error)

func (*Transaction) ValidateSize

func (t *Transaction) ValidateSize() bool

type TransactionPool

type TransactionPool map[string]Transaction

type WorkLeaf

type WorkLeaf struct {
	Count  int64
	Proofs map[string]WorkProof
}

stores proofs and counts

type WorkProof

type WorkProof struct {
	Address string `json:"address"`
	Block   Block  `json:"block"`
}

stores the dedicated proof block

type WorkTrie

type WorkTrie struct {
	Members map[string]WorkLeaf
}

stores proof groups per address

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL