blockchain

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2025 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned when an entity is not found

Functions

func CreateDummyContractManifest

func CreateDummyContractManifest(name, description string) json.RawMessage

CreateDummyContractManifest creates a dummy contract manifest for testing

func SetupTestContract

func SetupTestContract(t *testing.T, client *MockClient, contractHash string, methods map[string]interface{})

SetupTestContract sets up a mock smart contract in the blockchain client

Types

type Balance

type Balance struct {
	Asset   string `json:"asset"`
	Address string `json:"address"`
	Amount  string `json:"amount"`
}

Balance represents an account's token balance

type BlockchainClient

type BlockchainClient interface {
	// Core blockchain operations
	GetBlockHeight() (uint32, error)
	GetBlock(height uint32) (interface{}, error)
	GetTransaction(hash string) (interface{}, error)
	SendTransaction(tx interface{}) (string, error)

	// Smart contract operations
	InvokeContract(contractHash string, method string, params []interface{}) (map[string]interface{}, error)
	DeployContract(ctx context.Context, nefFile []byte, manifest json.RawMessage) (string, error)
	SubscribeToEvents(ctx context.Context, contractHash, eventName string, handler func(event interface{})) error

	// Transaction operations
	GetTransactionReceipt(ctx context.Context, hash string) (interface{}, error)
	IsTransactionInMempool(ctx context.Context, hash string) (bool, error)

	// Client management
	CheckHealth(ctx context.Context) error
	ResetConnections()
	Close() error
}

BlockchainClient defines the interface for interacting with the blockchain

func SetupTestBlockchain

func SetupTestBlockchain(t *testing.T) (BlockchainClient, func())

SetupTestBlockchain creates a mock blockchain client for testing

type BlockchainClientFactory

type BlockchainClientFactory interface {
	// Create a new production blockchain client
	NewClient() (BlockchainClient, error)

	// Create a mock blockchain client for testing
	NewMockClient() BlockchainClient
}

BlockchainClientFactory creates blockchain clients

Factory a global factory for blockchain clients

func NewClientFactory

func NewClientFactory(cfg *config.Config, log *logger.Logger) BlockchainClientFactory

NewClientFactory creates a new blockchain client factory

func SetupTestFactory

func SetupTestFactory(t *testing.T) BlockchainClientFactory

SetupTestFactory creates a blockchain client factory for testing

type Client

type Client interface {
	// Contract operations
	InvokeContractFunction(scriptHash string, method string, args []interface{}) (*InvokeResult, error)
	GetContractStorage(scriptHash string, key string) (string, error)
	DeployContract(ctx interface{}, contract *ContractDeployment) (*DeployResult, error)

	// Transaction operations
	GetTransactionInfo(txID string) (*TransactionInfo, error)

	// Blockchain query operations
	GetBlockHeight() (uint32, error)

	// Asset operations
	GetBalance(address string, assetID string) (*Balance, error)
	Transfer(fromAddress string, toAddress string, amount string, assetID string) (*TransferResult, error)
}

Client defines the interface for blockchain operations

func NewClient

func NewClient(cfg *config.NeoConfig, log *logger.Logger, nodes []NodeConfig) (*Client, error)

NewClient creates a new blockchain client

func (*Client) CheckHealth

func (c *Client) CheckHealth(ctx context.Context) error

CheckHealth verifies that nodes are responding correctly

func (*Client) Close

func (c *Client) Close() error

Close closes the blockchain client

func (*Client) CurrentBlockHeight

func (c *Client) CurrentBlockHeight() uint32

CurrentBlockHeight returns the cached block height

func (*Client) DeployContract

func (c *Client) DeployContract(ctx context.Context, nefFile []byte, manifest json.RawMessage, signers []interface{}, privateKey *wallet.PrivateKey) (string, error)

DeployContract deploys a smart contract to the Neo N3 blockchain

func (*Client) GetBlock

func (c *Client) GetBlock(height uint32) (*block.Block, error)

GetBlock returns a block by height

func (*Client) GetBlockHeight

func (c *Client) GetBlockHeight() (uint32, error)

GetBlockHeight returns the current block height

func (*Client) GetTransaction

func (c *Client) GetTransaction(hash string) (*transaction.Transaction, error)

GetTransaction returns a transaction by hash

func (*Client) GetTransactionReceipt

func (c *Client) GetTransactionReceipt(ctx context.Context, hash string) (*TransactionReceipt, error)

GetTransactionReceipt gets the receipt for a transaction

func (*Client) InvokeContract

func (c *Client) InvokeContract(contractHash string, method string, params []interface{}) (map[string]interface{}, error)

InvokeContract invokes a smart contract read-only method

func (*Client) InvokeFunction

func (c *Client) InvokeFunction(contractHash, operation string, params []client.StackItem) (interface{}, error)

InvokeFunction invokes a smart contract function

func (*Client) IsTransactionInMempool

func (c *Client) IsTransactionInMempool(ctx context.Context, hash string) (bool, error)

IsTransactionInMempool checks if a transaction is in the mempool

func (*Client) LoadWallet

func (c *Client) LoadWallet(path, password string) (*wallet.Wallet, error)

LoadWallet loads a NEP-6 wallet

func (*Client) ResetConnections

func (c *Client) ResetConnections()

ResetConnections forces the client to reset any cached connections

func (*Client) SendTransaction

func (c *Client) SendTransaction(tx *transaction.Transaction) (string, error)

SendTransaction sends a signed transaction to the blockchain

func (*Client) SubscribeToEvents

func (c *Client) SubscribeToEvents(ctx context.Context, contractHash, eventName string, handler func(event interface{})) error

SubscribeToEvents subscribes to blockchain events

func (*Client) TransferAsset

func (c *Client) TransferAsset(ctx context.Context, asset string, from string, to string, amount float64, privateKey *wallet.PrivateKey) (string, error)

TransferAsset transfers an asset on the Neo N3 blockchain

type ClientFactory

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

ClientFactory is an implementation of BlockchainClientFactory

func (*ClientFactory) NewClient

func (f *ClientFactory) NewClient() (BlockchainClient, error)

NewClient creates a new blockchain client

func (*ClientFactory) NewMockClient

func (f *ClientFactory) NewMockClient() BlockchainClient

NewMockClient creates a new mock blockchain client for testing

type CompilerClient

type CompilerClient struct {
}

CompilerClient provides access to NEO contract compilation

type ContractDeployment

type ContractDeployment struct {
	Name        string            `json:"name"`
	Description string            `json:"description"`
	NEF         []byte            `json:"nef"`
	Manifest    string            `json:"manifest"`
	Parameters  map[string]string `json:"parameters"`
}

ContractDeployment represents the data needed to deploy a smart contract

type ContractService

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

ContractService provides functionality for contract deployment and verification

func NewContractService

func NewContractService(
	client *Client,
	walletStore WalletStore,
	contractRepo *database.ContractRepository,
	logger *logger.Logger,
) *ContractService

NewContractService creates a new contract service

func (*ContractService) DeployContract

DeployContract deploys a smart contract to the blockchain

func (*ContractService) GetContract

func (s *ContractService) GetContract(ctx context.Context, id string) (*models.ContractResponse, error)

GetContract retrieves a contract by ID

func (*ContractService) GetContractsByUser

func (s *ContractService) GetContractsByUser(ctx context.Context, userID int) ([]*models.ContractResponse, error)

GetContractsByUser retrieves contracts by user ID

func (*ContractService) VerifyContract

VerifyContract verifies a contract's source code

type DBWalletStore

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

DBWalletStore provides access to wallet storage via database

func NewDBWalletStore

func NewDBWalletStore(db *sqlx.DB, logger *logger.Logger, cfg *config.NeoConfig, encryptionKey string) (*DBWalletStore, error)

NewDBWalletStore creates a new wallet store

func (*DBWalletStore) ClearCache

func (s *DBWalletStore) ClearCache()

ClearCache clears the wallet cache

func (*DBWalletStore) CreateWallet

func (s *DBWalletStore) CreateWallet(ctx context.Context, userID int, name, password string) (string, error)

CreateWallet creates a new wallet for a user

func (*DBWalletStore) DeleteWallet

func (s *DBWalletStore) DeleteWallet(ctx context.Context, userID int, walletID string) error

DeleteWallet deletes a wallet

func (*DBWalletStore) GetWallet

func (s *DBWalletStore) GetWallet(userID int, walletID string) (*wallet.Wallet, error)

GetWallet retrieves a wallet by user ID and wallet ID

func (*DBWalletStore) ListWallets

func (s *DBWalletStore) ListWallets(ctx context.Context, userID int) ([]WalletData, error)

ListWallets lists all wallets for a user

type DefaultEventProcessor

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

DefaultEventProcessor processes blockchain events and notifies subscribers

func NewEventProcessor

func NewEventProcessor(
	eventRepo *database.EventRepository,
	logger *logger.Logger,
	config *EventProcessorConfig,
) *DefaultEventProcessor

NewEventProcessor creates a new event processor

func (*DefaultEventProcessor) ProcessEvent

func (p *DefaultEventProcessor) ProcessEvent(event *models.BlockchainEvent) error

ProcessEvent processes a blockchain event

type DeployResult

type DeployResult struct {
	Success       bool   `json:"success"`
	ScriptHash    string `json:"script_hash"`
	TransactionID string `json:"transaction_id"`
	GasConsumed   string `json:"gas_consumed"`
}

DeployResult represents the result of a contract deployment

type EventMonitor

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

EventMonitor continuously monitors the blockchain for events

func NewEventMonitor

func NewEventMonitor(
	client *Client,
	eventRepo *database.EventRepository,
	eventProcessor EventProcessor,
	logger *logger.Logger,
	config *EventMonitorConfig,
) *EventMonitor

NewEventMonitor creates a new event monitor

func (*EventMonitor) Start

func (m *EventMonitor) Start() error

Start starts the event monitor

func (*EventMonitor) Stop

func (m *EventMonitor) Stop() error

Stop stops the event monitor

type EventMonitorConfig

type EventMonitorConfig struct {
	Network          string
	SyncInterval     time.Duration
	BatchSize        int
	ReorgThreshold   int
	MaxRetries       int
	RetryInterval    time.Duration
	StartBlockOffset int
}

EventMonitorConfig contains configuration for the event monitor

type EventProcessor

type EventProcessor interface {
	ProcessEvent(event *models.BlockchainEvent) error
}

EventProcessor processes blockchain events and notifies subscribers

type EventProcessorConfig

type EventProcessorConfig struct {
	WebhookTimeout    time.Duration
	MaxRetryCount     int
	RetryBackoff      time.Duration
	MaxConcurrentJobs int
}

EventProcessorConfig contains configuration for the event processor

type InvocationResult

type InvocationResult struct {
	State       string        `json:"state"`
	GasConsumed string        `json:"gasConsumed"`
	Stack       []interface{} `json:"stack"`
}

InvocationResult contains the result of a contract invocation.

type InvokeResult

type InvokeResult struct {
	Success       bool              `json:"success"`
	TransactionID string            `json:"transaction_id"`
	GasConsumed   string            `json:"gas_consumed"`
	Result        map[string]string `json:"result"`
}

InvokeResult represents the result of a smart contract invocation

type MockClient

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

MockClient is a mock implementation of the blockchain client for testing

func NewMockClient

func NewMockClient(log *logger.Logger) *MockClient

NewMockClient creates a new mock blockchain client

func (*MockClient) CheckHealth

func (c *MockClient) CheckHealth(ctx context.Context) error

CheckHealth verifies that nodes are responding correctly

func (*MockClient) Close

func (c *MockClient) Close() error

Close closes the blockchain client

func (*MockClient) DeployContract

func (c *MockClient) DeployContract(ctx context.Context, nefFile []byte, manifest json.RawMessage) (string, error)

DeployContract deploys a smart contract

func (*MockClient) EmitEvent

func (c *MockClient) EmitEvent(contractHash, eventName string, data interface{})

EmitEvent emits a mock event

func (*MockClient) GetBlock

func (c *MockClient) GetBlock(height uint32) (interface{}, error)

GetBlock returns a block by height

func (*MockClient) GetBlockHeight

func (c *MockClient) GetBlockHeight() (uint32, error)

GetBlockHeight returns the current block height

func (*MockClient) GetTransaction

func (c *MockClient) GetTransaction(hash string) (interface{}, error)

GetTransaction returns a transaction by hash

func (*MockClient) GetTransactionReceipt

func (c *MockClient) GetTransactionReceipt(ctx context.Context, hash string) (interface{}, error)

GetTransactionReceipt gets the receipt for a transaction

func (*MockClient) InvokeContract

func (c *MockClient) InvokeContract(contractHash string, method string, params []interface{}) (map[string]interface{}, error)

InvokeContract invokes a smart contract

func (*MockClient) IsTransactionInMempool

func (c *MockClient) IsTransactionInMempool(ctx context.Context, hash string) (bool, error)

IsTransactionInMempool checks if a transaction is in the mempool

func (*MockClient) ResetConnections

func (c *MockClient) ResetConnections()

ResetConnections forces the client to reset connections

func (*MockClient) SendTransaction

func (c *MockClient) SendTransaction(tx interface{}) (string, error)

SendTransaction sends a signed transaction to the blockchain

func (*MockClient) SetBlockHeight

func (c *MockClient) SetBlockHeight(height uint32)

SetBlockHeight sets the mock block height

func (*MockClient) SetContractCallResult

func (c *MockClient) SetContractCallResult(contractHash, method string, result interface{})

SetContractCallResult sets the result for a specific contract method call

func (*MockClient) SetTransaction

func (c *MockClient) SetTransaction(hash string, data []byte)

SetTransaction adds a mock transaction

func (*MockClient) SubscribeToEvents

func (c *MockClient) SubscribeToEvents(ctx context.Context, contractHash, eventName string, handler func(event interface{})) error

SubscribeToEvents subscribes to blockchain events

type MockTransactionReceipt

type MockTransactionReceipt struct {
	Hash          string          `json:"hash"`
	Confirmations int64           `json:"confirmations"`
	BlockHeight   int64           `json:"blockHeight"`
	BlockTime     time.Time       `json:"blockTime"`
	GasConsumed   int64           `json:"gasConsumed"`
	Result        json.RawMessage `json:"result"`
}

TransactionReceipt contains information about a blockchain transaction

type NodeConfig

type NodeConfig struct {
	URL    string  `json:"url"`
	Weight float64 `json:"weight"`
}

NodeConfig represents a Neo N3 node configuration

type ServiceWalletStore

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

ServiceWalletStore provides functionality for managing service wallets

func NewServiceWalletStore

func NewServiceWalletStore(config *config.Config, logger *logger.Logger, db *sqlx.DB) *ServiceWalletStore

NewServiceWalletStore creates a new wallet store

func (*ServiceWalletStore) ClearCache

func (s *ServiceWalletStore) ClearCache()

ClearCache clears the wallet cache

func (*ServiceWalletStore) CreateWallet

func (s *ServiceWalletStore) CreateWallet(ctx context.Context, service string) (*models.WalletAccount, error)

CreateWallet creates a new wallet for a service

func (*ServiceWalletStore) GetPrivateKey

func (s *ServiceWalletStore) GetPrivateKey(ctx context.Context, walletID uuid.UUID) (string, error)

GetPrivateKey retrieves the private key for a wallet

type Signer

type Signer struct {
	Account string `json:"account"`
	Scopes  string `json:"scopes"`
}

Signer represents a transaction signer.

type Transaction

type Transaction struct {
	ID        string `json:"id"`
	Size      int    `json:"size"`
	Hash      string `json:"hash"`
	BlockHash string `json:"blockHash"`
	BlockTime int64  `json:"blockTime"`
	Sender    string `json:"sender"`
}

Transaction represents a blockchain transaction.

type TransactionInfo

type TransactionInfo struct {
	TransactionID string    `json:"transaction_id"`
	BlockHash     string    `json:"block_hash"`
	BlockHeight   uint32    `json:"block_height"`
	Timestamp     time.Time `json:"timestamp"`
	Sender        string    `json:"sender"`
	Status        string    `json:"status"`
	GasConsumed   string    `json:"gas_consumed"`
}

TransactionInfo represents detailed information about a blockchain transaction

type TransactionParams

type TransactionParams struct {
	ScriptHash string        `json:"scriptHash"`
	Operation  string        `json:"operation"`
	Params     []interface{} `json:"params"`
	Signers    []Signer      `json:"signers"`
}

TransactionParams contains parameters for creating a transaction.

type TransactionReceipt

type TransactionReceipt struct {
	Hash          string          `json:"hash"`
	Confirmations int64           `json:"confirmations"`
	BlockHeight   int64           `json:"blockHeight"`
	BlockTime     time.Time       `json:"blockTime"`
	GasConsumed   int64           `json:"gasConsumed"`
	Result        json.RawMessage `json:"result"`
}

TransactionReceipt contains information about a blockchain transaction

type TransactionService

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

TransactionService provides functionality for managing blockchain transactions

func NewTransactionService

func NewTransactionService(
	repo database.TransactionRepository,
	client *Client,
	walletStore *WalletStore,
	confirmations int64,
) *TransactionService

NewTransactionService creates a new TransactionService

func NewTransactionServiceWithFactory

func NewTransactionServiceWithFactory(
	factory *database.RepositoryFactory,
	client *Client,
	walletStore *WalletStore,
	confirmations int64,
	useOptimizedRepo bool,
) *TransactionService

NewTransactionServiceWithFactory creates a new TransactionService with the repository factory

func (*TransactionService) CancelTransaction

func (s *TransactionService) CancelTransaction(ctx context.Context, id uuid.UUID) (*models.Transaction, error)

CancelTransaction cancels a pending transaction

func (*TransactionService) CheckHealth

func (s *TransactionService) CheckHealth(ctx context.Context) error

CheckHealth checks if the blockchain client is healthy

func (*TransactionService) CreateServiceWallet

func (s *TransactionService) CreateServiceWallet(ctx context.Context, service string) (*models.WalletAccount, error)

CreateServiceWallet creates a new wallet for a service

func (*TransactionService) CreateTransaction

CreateTransaction creates a new transaction and submits it to the blockchain

func (*TransactionService) GetServiceWallet

func (s *TransactionService) GetServiceWallet(ctx context.Context, service string) (*models.WalletAccount, error)

GetServiceWallet gets the wallet for a service

func (*TransactionService) GetTransaction

func (s *TransactionService) GetTransaction(ctx context.Context, id uuid.UUID) (*models.Transaction, error)

GetTransaction retrieves a transaction by ID

func (*TransactionService) GetTransactionByHash

func (s *TransactionService) GetTransactionByHash(ctx context.Context, hash string) (*models.Transaction, error)

GetTransactionByHash retrieves a transaction by hash

func (*TransactionService) GetTransactionEvents

func (s *TransactionService) GetTransactionEvents(ctx context.Context, transactionID uuid.UUID) ([]models.TransactionEvent, error)

GetTransactionEvents retrieves events for a transaction

func (*TransactionService) ListServiceWallets

func (s *TransactionService) ListServiceWallets(ctx context.Context, service string) ([]models.WalletAccount, error)

ListServiceWallets lists all wallets for a service

func (*TransactionService) ListTransactions

func (s *TransactionService) ListTransactions(
	ctx context.Context,
	service string,
	status models.TransactionStatus,
	entityID *uuid.UUID,
	page, limit int,
) (*models.TransactionListResponse, error)

ListTransactions lists transactions with filtering

func (*TransactionService) RetryTransaction

func (s *TransactionService) RetryTransaction(ctx context.Context, id uuid.UUID) (*models.Transaction, error)

RetryTransaction retries a failed or expired transaction

func (*TransactionService) StartMonitoring

func (s *TransactionService) StartMonitoring(ctx context.Context)

StartMonitoring starts monitoring pending transactions

type TransferResult

type TransferResult struct {
	Success       bool   `json:"success"`
	TransactionID string `json:"transaction_id"`
	FromAddress   string `json:"from_address"`
	ToAddress     string `json:"to_address"`
	Asset         string `json:"asset"`
	Amount        string `json:"amount"`
}

TransferResult represents the result of a token transfer

type WalletData

type WalletData struct {
	ID           uuid.UUID `db:"id"`
	UserID       int       `db:"user_id"`
	Name         string    `db:"name"`
	EncryptedKey []byte    `db:"encrypted_key"`
	Path         string    `db:"path"`
	IV           []byte    `db:"iv"`
	CreatedAt    time.Time `db:"created_at"`
	UpdatedAt    time.Time `db:"updated_at"`
}

WalletData represents the wallet data stored in the database

type WalletStore

type WalletStore interface {
	GetWallet(userID int, walletID string) (*wallet.Wallet, error)
}

WalletStore provides access to wallet storage

Directories

Path Synopsis
Package compat provides compatibility layers for external dependencies
Package compat provides compatibility layers for external dependencies
Package mock provides mock implementations for blockchain components.
Package mock provides mock implementations for blockchain components.

Jump to

Keyboard shortcuts

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