types

package
v0.0.0-...-d0f1153 Latest Latest
Warning

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

Go to latest
Published: May 27, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

types/sharding.go

types/utxo_utils.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MarkUTXOAsSpent

func MarkUTXOAsSpent(utxoID string, allUTXOs map[string]UTXO)

MarkUTXOAsSpent removes a UTXO from the set of available UTXOs

Types

type AdaptiveConsensus

type AdaptiveConsensus struct {
	Params         map[int]*ConsensusParams
	Metrics        *StateMetrics
	UpdateInterval time.Duration
	StopChan       chan struct{}
	Mu             sync.RWMutex
}

type AddUTXORequest

type AddUTXORequest struct {
	UTXO UTXO
}

type BalanceNotifier

type BalanceNotifier interface {
	SendBalanceUpdate(address string) error
	NotifyBalanceUpdate(address string, balance amount.Amount)
}

type BalanceUpdateRequest

type BalanceUpdateRequest struct {
	Address string
	Retries int
}

type BeaconChain

type BeaconChain struct {
	// Blocks specific to the Beacon Chain
	Blocks   []*Block
	Mu       sync.RWMutex
	Database Store // Dedicated DB for beacon chain

}

BeaconChain represents the global coordination chain.

type Block

type Block struct {
	Index              int64            `cbor:"1,keyasint"`
	Timestamp          int64            `cbor:"2,keyasint"`
	PrevHash           hash.Hash        `cbor:"4,keyasint"`
	TransactionsRoot   []byte           `cbor:"4,keyasint"`
	Hash               hash.Hash        `cbor:"5,keyasint,omitempty"`
	Transactions       []*Transaction   `cbor:"6,keyasint"`
	Data               string           `cbor:"7,keyasint,omitempty"`
	ValidatorPublicKey crypto.PublicKey `cbor:"8,keyasint"`
	Signature          crypto.Signature `cbor:"9,keyasint,omitempty"`
	Salt               []byte           `cbor:"10,keyasint"`
	Validator          string           `cbor:"11,keyasint"`
}

Block represents a single unit of data within the blockchain

func (*Block) Marshal

func (b *Block) Marshal() ([]byte, error)

Basic methods that don't require chain-specific logic

func (*Block) Unmarshal

func (b *Block) Unmarshal(data []byte) error

type Blockchain

type Blockchain struct {
	// Blocks holds the sequence of blocks that constitute the blockchain. Each block contains
	// a set of transactions and is linked to the previous block, forming the chain.
	Blocks []*Block

	// Genesis points to the first block in the blockchain, known as the Genesis block. This block
	// is the foundation of the blockchain, with no preceding block.
	Genesis *Block

	// Adding transactions to the pending transactions pool
	PendingTransactions []*thrylos.Transaction

	// Stakeholders maps validator addresses to their respective stakes in the network. This is
	// used in proof-of-stake (PoS) consensus mechanisms to determine validators' rights to create
	// new blocks based on the size of their stake
	Stakeholders map[string]int64 // Maps validator addresses to their respective stakes

	// UTXOs tracks unspent transaction outputs, which represent the current state of ownership
	// of the blockchain's assets. It is a key component in preventing double spending.
	UTXOs map[string][]*thrylos.UTXO

	// Forks captures any divergences in the blockchain, where two or more blocks are found to
	// have the same predecessor. Forks are resolved through mechanisms that ensure consensus
	// on a single chain.
	Forks []*Fork

	// Mu provides concurrency control to ensure that operations on the blockchain are thread-safe,
	// preventing race conditions and ensuring data integrity.
	Mu sync.RWMutex

	// lastTimestamp records the timestamp of the last added block. This is used to ensure that
	// blocks are added in chronological order, preserving the integrity of the blockchain's timeline.
	LastTimestamp int64

	// Database provides an abstraction over the underlying database technology used to persist
	// blockchain data, facilitating operations like adding blocks and retrieving blockchain state
	Database Store // Updated the type to interface

	PublicKeyMap map[string]*crypto.PublicKey // To store public keys

	GenesisAccount crypto.PrivateKey // Add this to store the genesis account address

	ConsensusManager *ConsensusManager

	ActiveValidators []string

	NextValidatorIndex int

	MinStakeForValidator *big.Int

	OnNewBlock func(*Block) // Callback function for when a new block is added

	ValidatorKeys          ValidatorKeyStore // Changed from *ValidatorKeyStore to ValidatorKeyStore
	TestMode               bool
	OnTransactionProcessed func(*thrylos.Transaction)
	OnBalanceUpdate        func(address string, balance int64)

	StateManager *StateManager

	StateNetwork   NetworkInterface
	StakingService *StakingService

	TransactionPropagator *TransactionPropagator

	LocalShardID ShardID
	ShardStates  map[ShardID]*ChainState

	Beacon           *BeaconChain
	GlobalMessageBus MessageBusInterface
	Libp2pManager    NetworkInterface
	AppConfig        *config.Config
}

// // Blockchain represents the entire blockchain structure, encapsulating all blocks, stakeholders, // // and transactions within the network. It serves as the central ledger of the system, tracking // // the state of the blockchain, including ownership of assets through UTXOs (Unspent Transaction Outputs), // // and the resolution of forks, ensuring the integrity and continuity of the chain.

type BlockchainConfig

type BlockchainConfig struct {
	DataDir           string
	AESKey            []byte
	GenesisAccount    crypto.PrivateKey
	TestMode          bool
	DisableBackground bool
	StateManager      *StateManager
}

type BlockchainInterface

type BlockchainInterface interface {
	GetTotalSupply() int64
	IsActiveValidator(address string) bool
	UpdateActiveValidators(count int)
	GetValidatorPublicKey(validator string) (*mldsa44.PublicKey, error)
	RetrievePublicKey(validator string) ([]byte, error)
	GetMinStakeForValidator() *big.Int
	Stakeholders() map[string]int64
	GetActiveValidators() []string // Add this method to the interface

}

type ChainState

type ChainState struct {
	ShardID        ShardID // Identifier for this shard
	TotalNumShards int     // NEW: Total number of shards in the network
	Blocks         []*Block
	Genesis        *Block

	// PendingTransactions: Will be moved to a shard-specific TxPool.
	PendingTransactions    []*thrylos.Transaction
	Stakeholders           map[string]int64
	UTXOs                  map[string][]*thrylos.UTXO // Still uses *thrylos.UTXO internally
	Forks                  []*Fork                    // Forks within this specific shard chain
	Mu                     sync.RWMutex               // This mutex protects only THIS shard's state
	LastTimestamp          int64
	Database               Store // Store interface, but implementation will be shard-aware
	PublicKeyMap           map[string]*crypto.PublicKey
	GenesisAccount         crypto.PrivateKey
	ConsensusManager       *ConsensusManager
	ActiveValidators       []string
	NextValidatorIndex     int
	MinStakeForValidator   *big.Int
	OnNewBlock             func(*Block)
	ValidatorKeys          ValidatorKeyStore
	TestMode               bool
	OnTransactionProcessed func(*thrylos.Transaction)
	OnBalanceUpdate        func(address string, balance int64)
	StateManager           *StateManager
	StateNetwork           NetworkInterface
	StakingService         *StakingService
	TransactionPropagator  *TransactionPropagator
}

ChainState represents the state specific to a single shard chain. This is effectively your current 'types.Blockchain' struct, but renamed and modified.

type ConnectionStatus

type ConnectionStatus struct {
	Address         string    `json:"address"`
	Connected       bool      `json:"connected"`
	LastConnected   time.Time `json:"lastConnected"`
	ReconnectCount  int       `json:"reconnectCount"`
	QueueSize       int       `json:"queueSize"`
	IsReconnecting  bool      `json:"isReconnecting"`
	LastMessageSent time.Time `json:"lastMessageSent"`
}

Add ConnectionStatus struct

type ConsensusManager

type ConsensusManager struct {
	Blockchain       BlockchainInterface
	CurrentBlockTime time.Duration
	PredictionModel  *PredictionModel
	// contains filtered or unexported fields
}

func (*ConsensusManager) GetMaliciousDetector

func (cm *ConsensusManager) GetMaliciousDetector() *detection.MaliciousDetector

GetMaliciousDetector allows retrieving the maliciousDetector

func (*ConsensusManager) SetMaliciousDetector

func (cm *ConsensusManager) SetMaliciousDetector(detector *detection.MaliciousDetector)

SetMaliciousDetector allows setting the maliciousDetector field

type ConsensusParams

type ConsensusParams struct {
	BlockSize        int
	ConfirmationTime time.Duration
	MinValidators    int
	Threshold        float64
}

type DAGTipsResponse

type DAGTipsResponse struct {
	Tips  []string
	Error error
}

type Fork

type Fork struct {
	Index  int
	Blocks []*Block
}

// Fork structure representing a fork in the blockchain

type FundAddressRequest

type FundAddressRequest struct {
	Address string
	Amount  amount.Amount // Change from int64 to amount.Amount
}

type IsCounterNodeResponse

type IsCounterNodeResponse struct {
	IsCounter bool
	Error     error
}

type Message

type Message struct {
	Type       MessageType
	Data       interface{}
	ResponseCh chan Response
}

Message represents a generic message in the system

type MessageBus

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

MessageBus handles communication between packages

func (*MessageBus) Close

func (mb *MessageBus) Close()

Close closes all subscriber channels

func (*MessageBus) Publish

func (mb *MessageBus) Publish(msg Message)

Publish sends a message to all subscribers of the message type

func (*MessageBus) Subscribe

func (mb *MessageBus) Subscribe(msgType MessageType, ch chan Message)

Subscribe adds a channel to receive messages of the specified type

func (*MessageBus) Unsubscribe

func (mb *MessageBus) Unsubscribe(msgType MessageType, ch chan Message)

Unsubscribe removes a channel from receiving messages of the specified type

type MessageBusInterface

type MessageBusInterface interface {
	Subscribe(msgType MessageType, ch chan Message) // Use chan Message directly
	Unsubscribe(msgType MessageType, ch chan Message)
	Publish(msg Message)
	Close()
}

func GetGlobalMessageBus

func GetGlobalMessageBus() MessageBusInterface

GetGlobalMessageBus returns the singleton message bus instance

type MessageChannel

type MessageChannel = chan Message // Using type alias for clarity

Message channel type

type MessageItem

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

type MessageType

type MessageType string

MessageType represents different types of messages that can be sent

const (
	// Balance related
	GetBalance            MessageType = "GET_BALANCE"
	GetUTXOs              MessageType = "GET_UTXOS"
	AddUTXO               MessageType = "ADD_UTXO"
	UpdateState           MessageType = "UPDATE_STATE"
	FundNewAddress        MessageType = "FUND_NEW_ADDRESS"
	GetStakeholderBalance MessageType = "GET_STAKEHOLDER_BALANCE"

	// Transaction related
	ProcessTransaction         MessageType = "PROCESS_TRANSACTION"
	GetPendingTransactionCount MessageType = "GET_PENDING_TX_COUNT"
	GetPendingTransactionBatch MessageType = "GET_PENDING_TX_BATCH"
	UpdateProcessorState       MessageType = "UPDATE_PROCESSOR_STATE"
	EstimateGas                MessageType = "ESTIMATE_GAS"

	// Validator related
	SelectValidator            MessageType = "SELECT_VALIDATOR"
	ProcessValidatorVote       MessageType = "PROCESS_VALIDATOR_VOTE"
	HasSuperMajority           MessageType = "HAS_SUPER_MAJORITY"
	GetActiveValidators        MessageType = "GET_ACTIVE_VALIDATORS"
	GetStakeholders            MessageType = "GET_STAKEHOLDERS"
	IsActiveValidator          MessageType = "IS_ACTIVE_VALIDATOR"
	ProcessPendingTransactions MessageType = "PROCESS_PENDING_TRANSACTIONS"
	ConfirmBlock               MessageType = "CONFIRM_BLOCK"

	// Block related
	ProcessBlock      MessageType = "PROCESS_BLOCK"
	ValidateBlock     MessageType = "VALIDATE_BLOCK"
	HasBlock          MessageType = "HAS_BLOCK"
	GetConsensusTime  MessageType = "GET_CONSENSUS_TIME"
	GetPendingTxCount MessageType = "GET_PENDING_TX_COUNT"
	GetPendingTxBatch MessageType = "GET_PENDING_TX_BATCH"
	BroadcastVote     MessageType = "BROADCAST_VOTE"
	CreateBlock       MessageType = "CREATE_BLOCK"

	// DAG related
	ValidateDAGTx  MessageType = "VALIDATE_DAG_TX"
	UpdateDAGState MessageType = "UPDATE_DAG_STATE"
	GetDAGTips     MessageType = "GET_DAG_TIPS"

	// Node state related
	GetStakingStats      MessageType = "GET_STAKING_STATS"
	CreateStake          MessageType = "CREATE_STAKE"
	UpdatePeerList       MessageType = "UPDATE_PEER_LIST"
	IsCounterNode        MessageType = "IS_COUNTER_NODE"
	ValidateValidator    MessageType = "VALIDATE_VALIDATOR"
	GetPoolStats         MessageType = "GET_POOL_STATS"
	GetValidators        MessageType = "GET_VALIDATORS"
	IsValidator          MessageType = "IS_VALIDATOR"
	AddTransactionToPool MessageType = "ADD_TRANSACTION_TO_POOL"

	GetBlockchainInfo   MessageType = "GET_BLOCKCHAIN_INFO"
	GetBlocksFromHeight MessageType = "GET_BLOCKS_FROM_HEIGHT"
	ProcessVote         MessageType = "PROCESS_VOTE"
)

type NetworkInterface

type NetworkInterface interface {
	SendMessage(nodeAddress string, message []byte) error
	BroadcastMessage(message []byte) error
	GetPeerAddresses() []string
	IsConnected(nodeAddress string) bool
	AddPeer(address string)
	RemovePeer(address string)
}

NetworkInterface defines the methods required for network communication

type NetworkMessage

type NetworkMessage struct {
	Type      string      `json:"type"`
	Data      interface{} `json:"data"`
	Timestamp time.Time   `json:"timestamp"`
}

type PendingBalanceUpdate

type PendingBalanceUpdate struct {
	Address   string
	Balance   int64
	Timestamp time.Time
}

type PendingTransactionBatchRequest

type PendingTransactionBatchRequest struct {
	BatchSize int
}

type PendingTransactionBatchResponse

type PendingTransactionBatchResponse struct {
	Transactions []*Transaction
	Error        error
}

type PendingTransactionCountResponse

type PendingTransactionCountResponse struct {
	Count int
	Error error
}

type PredictionModel

type PredictionModel struct {
	ExpectedTransactionVolume int
	ExpectedNodeCount         int
}

type RelocationCandidate

type RelocationCandidate struct {
	Address     string
	AccessCount int64
	FromShard   int
	ToShard     int
}

type Response

type Response struct {
	Data  interface{}
	Error error
}

Response represents a generic response

type ShardID

type ShardID int

ShardID type (new)

type ShardMetrics

type ShardMetrics struct {
	AccessCount int64
	ModifyCount int64
	LoadFactor  float64
	Latency     time.Duration
	LastUpdated time.Time
	Mu          sync.RWMutex // Export the mutex
}

func (*ShardMetrics) RecordAccess

func (sm *ShardMetrics) RecordAccess()

RecordAccess increments the access count for this shard

func (*ShardMetrics) RecordModify

func (sm *ShardMetrics) RecordModify()

RecordModify increments the modify count for this shard

func (*ShardMetrics) UpdateLoadFactor

func (sm *ShardMetrics) UpdateLoadFactor(itemCount int)

UpdateLoadFactor updates the load factor based on the current state

type ShardScaling

type ShardScaling struct {
	LoadThresholds struct {
		Split float64 // When to split a shard
		Merge float64 // When to consider merging shards
	}
	Limits struct {
		MinShards int
		MaxShards int
	}
	CooldownPeriod time.Duration // Now exported with capital C
	// contains filtered or unexported fields
}

In the types package, change:

func (*ShardScaling) GetCooldownPeriod

func (s *ShardScaling) GetCooldownPeriod() time.Duration

Access to ShardScaling's fields

func (*ShardScaling) GetLastScaleTime

func (s *ShardScaling) GetLastScaleTime() time.Time

func (*ShardScaling) Lock

func (s *ShardScaling) Lock()

func (*ShardScaling) SetLastScaleTime

func (s *ShardScaling) SetLastScaleTime(t time.Time)

func (*ShardScaling) Unlock

func (s *ShardScaling) Unlock()

type Stake

type Stake struct {
	UserAddress            string  `json:"userAddress"`
	Amount                 int64   `json:"amount"`
	StartTime              int64   `json:"startTime"`
	LastStakeUpdateTime    int64   `json:"lastStakeUpdateTime"` // Last time stake was updated
	StakeTimeSum           float64 `json:"stakeTimeSum"`        // Accumulated stake-time (stake * duration)
	StakeTimeAverage       float64 `json:"stakeTimeAverage"`    // Moving average of stake-time
	TotalStakeRewards      float64 `json:"totalStakeRewards"`
	TotalDelegationRewards float64 `json:"totalDelegationRewards"`
	IsActive               bool    `json:"isActive"`
	ValidatorRole          bool    `json:"validatorRole"`
}

type Stakeholder

type Stakeholder struct {
	Address string
	Stake   int
}

NewTransaction creates a new transaction

type StakingManager

type StakingManager interface {
	GetPoolStats() map[string]interface{}
	CreateStake(userAddress string, amount int64) (*Stake, error)
	UnstakeTokens(userAddress string, amount int64) error
	DelegateToPool(delegator string, amount int64) error
	UndelegateFromPool(delegator string, amount int64) error
	DistributeRewards() error
	GetTotalStaked() int64
	GetEffectiveInflationRate() float64
}

type StakingPool

type StakingPool struct {
	MinStakeAmount    int64 `json:"minStakeAmount"`
	MinDelegation     int64 `json:"minDelegation"`     // Added for pool delegations
	FixedYearlyReward int64 `json:"fixedYearlyReward"` // Always 4.8M
	TotalStaked       int64 `json:"totalStaked"`       // Track total stake for monitoring
	TotalDelegated    int64 `json:"totalDelegated"`    // Added for pool delegations
	LastRewardTime    int64 `json:"lastRewardTime"`    // Last reward distribution time (in seconds)
}

type StakingService

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

type StateManager

type StateManager struct {
	Scaling *ShardScaling // Add this field (using capital S for public access)
	// contains filtered or unexported fields
}

StateManager handles state sharding across the network

func (*StateManager) CloseStopChan

func (sm *StateManager) CloseStopChan()

CloseStopChan safely closes the stop channel

func (*StateManager) GetConsensus

func (sm *StateManager) GetConsensus() *AdaptiveConsensus

GetConsensus returns the consensus mechanism

func (*StateManager) GetMetrics

func (sm *StateManager) GetMetrics() *StateMetrics

GetMetrics returns the state metrics

func (*StateManager) GetMutex

func (sm *StateManager) GetMutex() *sync.RWMutex

GetMutex returns the state manager's mutex

func (*StateManager) GetNetwork

func (sm *StateManager) GetNetwork() NetworkInterface

GetNetwork returns the network interface

func (*StateManager) GetPartition

func (sm *StateManager) GetPartition(id int) *StatePartition

GetPartition returns a partition by ID

func (*StateManager) GetPartitions

func (sm *StateManager) GetPartitions() []*StatePartition

Access to StateManager's fields

func (*StateManager) GetShardLoadFactor

func (sm *StateManager) GetShardLoadFactor(shardID int) float64

func (*StateManager) GetShardMetrics

func (sm *StateManager) GetShardMetrics(shardID int) *ShardMetrics

GetShardMetrics returns the metrics for a specific shard

func (*StateManager) GetStopChan

func (sm *StateManager) GetStopChan() <-chan struct{}

func (*StateManager) InitStopChan

func (sm *StateManager) InitStopChan()

InitStopChan initializes the stop channel

func (*StateManager) Lock

func (sm *StateManager) Lock()

func (*StateManager) PartitionsCount

func (sm *StateManager) PartitionsCount() int

func (*StateManager) SetConsensus

func (sm *StateManager) SetConsensus(consensus *AdaptiveConsensus)

SetConsensus sets the consensus mechanism

func (*StateManager) SetMetrics

func (sm *StateManager) SetMetrics(metrics *StateMetrics)

SetMetrics sets the metrics

func (*StateManager) SetNetwork

func (sm *StateManager) SetNetwork(network NetworkInterface)

SetNetwork sets the network interface

func (*StateManager) SetPartitions

func (sm *StateManager) SetPartitions(partitions []*StatePartition)

SetPartitions sets the partitions

func (*StateManager) SetScaling

func (sm *StateManager) SetScaling(scaling *ShardScaling)

SetScaling sets the shard scaling

func (*StateManager) SetTotalShards

func (sm *StateManager) SetTotalShards(totalShards int)

SetTotalShards sets the total number of shards

func (*StateManager) Unlock

func (sm *StateManager) Unlock()

func (*StateManager) UpdatePartition

func (sm *StateManager) UpdatePartition(index int, partition *StatePartition)

UpdatePartition updates a partition at a specific index

type StateMetrics

type StateMetrics struct {
	ShardMetrics map[int]*ShardMetrics
	Mu           sync.RWMutex
}

type StateMetricsInterface

type StateMetricsInterface interface {
	NewStateMetrics(numShards int) *StateMetrics
}

type StatePartition

type StatePartition struct {
	ID           int
	StartAddress string
	EndAddress   string
	Balances     map[string]int64
	UTXOs        map[string]*UTXO
	LastUpdated  int64
	// contains filtered or unexported fields
}

// StatePartition represents the state data for a single shard

func (*StatePartition) GetBalances

func (p *StatePartition) GetBalances() map[string]int64

GetBalances returns a copy of the balances map

func (*StatePartition) GetUTXOs

func (p *StatePartition) GetUTXOs() map[string]*UTXO

GetUTXOs returns a copy of the UTXOs map

func (*StatePartition) Lock

func (p *StatePartition) Lock()

Lock acquires a write lock on the partition

func (*StatePartition) RLock

func (p *StatePartition) RLock()

RLock acquires a read lock on the partition

func (*StatePartition) RUnlock

func (p *StatePartition) RUnlock()

RUnlock releases a read lock on the partition

func (*StatePartition) Unlock

func (p *StatePartition) Unlock()

Unlock releases a write lock on the partition

type Store

type Store interface {
	//UTOX
	GetUTXO(addr address.Address) ([]*UTXO, error)
	AddUTXO(utxo UTXO) error
	GetAllUTXOs() (map[string][]UTXO, error)
	AddNewUTXO(ctx TransactionContext, utxo UTXO, totalNumShards int) error
	CreateAndStoreUTXO(id, txID string, index int, owner string, amount float64) error
	CreateUTXO(id, txID string, index int, address string, amount float64) (UTXO, error)
	UpdateUTXOs(inputs []UTXO, outputs []UTXO) error
	GetUTXOsForUser(address string) ([]UTXO, error)
	GetUTXOsForAddress(address string, totalNumShards int) ([]UTXO, error)
	MarkUTXOAsSpent(ctx TransactionContext, utxo UTXO, totalNumShards int) error

	RetrieveTransaction(txn *badger.Txn, transactionID string, shardID ShardID) (*Transaction, error)
	SendTransaction(fromAddress, toAddress string, amount int, privKey crypto.PrivateKey, totalNumShards int) (bool, error) // MODIFIED
	SaveTransaction(ctx TransactionContext, tx *Transaction, totalNumShards int) error                                      // MODIFIED (added ctx to align with common usage)
	GetTransaction(id string, shardID ShardID) (*Transaction, error)                                                        // MODIFIED
	ProcessTransaction(tx *Transaction, totalNumShards int) error                                                           // MODIFIED (assuming it orchestrates other sharded ops)
	AddTransaction(tx *thrylos.Transaction, shardID ShardID) error                                                          // MODIFIED (if thrylos.Transaction is stored directly per-shard)
	TransactionExists(ctx TransactionContext, txID string, shardID ShardID) (bool, error)                                   // MODIFIED
	SetTransaction(txn TransactionContext, key []byte, value []byte) error

	CommitTransaction(ctx TransactionContext) error
	BeginTransaction() (TransactionContext, error)
	RollbackTransaction(txn TransactionContext) error

	//Block
	GetLastBlock() (*Block, error)
	GetLastBlockNumber() (int, error)
	GetBlock(blockNumber uint32) (*Block, error)
	RetrieveBlock(shardID ShardID, blockNumber int) ([]byte, error) // MODIFIED: Added shardID

	GetLastBlockData(shardID ShardID) ([]byte, error)
	StoreBlock(blockData []byte, blockNumber int) error
	GetLastBlockIndex(shardID ShardID) (int, error)
	SaveBlock(blk *Block) error                                    // For Genesis
	SaveBlockWithContext(ctx TransactionContext, blk *Block) error // For AddBlockToChain
	AddToBalance(ctx TransactionContext, address string, amount int64, totalNumShards int) error
	SpendUTXO(ctx TransactionContext, utxoKey string, ownerAddress string, totalNumShards int) (amount int64, err error)

	//PublicKey
	GetPublicKey(addr address.Address) (crypto.PublicKey, error)
	SavePublicKey(pubKey crypto.PublicKey) error

	//Balance
	GetBalance(address string, utxos map[string][]UTXO) (amount.Amount, error)
	UpdateBalance(address string, balance int64) error

	// Close
	Close() error
	GetDataDir() string
	GetLockFilePath() string
}

type Subscription

type Subscription struct {
	Type      string                 `json:"type"`
	Addresses []string               `json:"addresses,omitempty"`
	Options   map[string]interface{} `json:"options,omitempty"`
}

type Transaction

type Transaction struct {
	ID               string           `cbor:"1,keyasint"`
	Timestamp        int64            `cbor:"2,keyasint"`
	Inputs           []UTXO           `cbor:"3,keyasint"`
	Outputs          []UTXO           `cbor:"4,keyasint"`
	EncryptedInputs  []byte           `cbor:"5,keyasint,omitempty"`
	EncryptedOutputs []byte           `cbor:"6,keyasint,omitempty"`
	EncryptedAESKey  []byte           `cbor:"7,keyasint"`
	PreviousTxIds    []string         `cbor:"8,keyasint"`
	SenderAddress    address.Address  `cbor:"9,keyasint"`
	SenderPublicKey  crypto.PublicKey `cbor:"10,keyasint"`
	Signature        crypto.Signature `cbor:"11,keyasint,omitempty"`
	GasFee           int              `cbor:"12,keyasint"`
	BlockHash        string           `cbor:"13,keyasint,omitempty"`
	Salt             []byte           `cbor:"14,keyasint,omitempty"`
	Status           string           `cbor:"15,keyasint,omitempty"`
}

Transaction defines the structure for blockchain transactions

func (*Transaction) IsFunding

func (tx *Transaction) IsFunding() bool

func (*Transaction) IsGenesis

func (tx *Transaction) IsGenesis() bool

func (*Transaction) Marshal

func (tx *Transaction) Marshal() ([]byte, error)

Marshal serializes the transaction into CBOR format

func (*Transaction) Unmarshal

func (tx *Transaction) Unmarshal(data []byte) error

Unmarshal deserializes the transaction from CBOR format

type TransactionContext

type TransactionContext interface {
	GetUTXOs() map[string][]UTXO
	SetUTXOs(utxos map[string][]UTXO)
	IsModified(key string) bool
	SetModified(key string)
	GetTransaction() *Transaction
	Commit() error
	Rollback() error
	GetBadgerTxn() *badger.Txn // Add this new method
}

TransactionContext interface defines the methods that must be implemented

type TransactionPropagator

type TransactionPropagator struct {
	Blockchain BlockchainInterface
	Mu         sync.RWMutex
}

type TxPool

type TxPool interface {
	AddTransaction(tx *Transaction) error
	RemoveTransaction(tx *Transaction) error
	GetTransaction(txID string) (*Transaction, error)
	RemoveTransactions(txs []*Transaction) error
	GetFirstTransaction() (*Transaction, error)
	GetAllTransactions() ([]*Transaction, error)
	BroadcastTransaction(tx *Transaction) error
	GetActiveValidators(tx *Transaction) error
	Size() int
}

type UTXO

type UTXO struct {
	ID            string        `cbor:"1,keyasint,omitempty"`
	Index         int           `cbor:"2,keyasint"`
	TransactionID string        `cbor:"3,keyasint"`
	OwnerAddress  string        `cbor:"4,keyasint"`
	Amount        amount.Amount `cbor:"5,keyasint"`
	IsSpent       bool          `cbor:"6,keyasint"`
}

UTXO represents an Unspent Transaction Output

func CreateUTXO

func CreateUTXO(id string, index int, txID string, owner string, coinAmount float64, isSpent bool) *UTXO

CreateUTXO creates a new UTXO instance

func (*UTXO) Key

func (u *UTXO) Key() string

func (*UTXO) Marshal

func (u *UTXO) Marshal() ([]byte, error)

func (*UTXO) Unmarshal

func (u *UTXO) Unmarshal(data []byte) error

func (*UTXO) Validate

func (u *UTXO) Validate() error

UTXO methods stay with the type

type UTXORequest

type UTXORequest struct {
	Address string
}

type UTXOResponse

type UTXOResponse struct {
	UTXOs []UTXO
	Error error
}

type UpdateDAGStateRequest

type UpdateDAGStateRequest struct {
	TransactionID string
	State         string
}

type UpdateProcessorStateRequest

type UpdateProcessorStateRequest struct {
	TransactionID string
	State         string
}

type UpdateStateRequest

type UpdateStateRequest struct {
	Address string
	Balance int64
}

type UpdateTransactionStateRequest

type UpdateTransactionStateRequest struct {
	TransactionID string
	State         string
}

type Validator

type Validator interface {
	Index() int32
	PrivateKey() *crypto.PrivateKey
	PublicKey() *crypto.PublicKey
	Address() *address.Address
	Stake() amount.Amount
	Marshal() ([]byte, error)
	Unmarshal(data []byte) error
}

Validator represents the basic validator information

type ValidatorKeyStore

type ValidatorKeyStore interface {
	StoreKey(address string, key *crypto.PrivateKey) error
	GetKey(address string) (*crypto.PrivateKey, bool)
	RemoveKey(address string) error
	HasKey(address string) bool
	GetAllAddresses() []string
}

ValidatorKeyStore defines the interface for validator key operations

type Vote

type Vote struct {
	ValidatorID    string    `json:"validator_id"`
	BlockNumber    int32     `json:"block_number"`
	BlockHash      string    `json:"block_hash,omitempty"`
	ValidationPass bool      `json:"validation_pass,omitempty"`
	Timestamp      time.Time `json:"timestamp"`
	VoterNode      string    `json:"voter_node"`
}

Jump to

Keyboard shortcuts

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