rpcserver

package
v0.0.0-...-7ece11e Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2023 License: MIT Imports: 88 Imported by: 2

README

This package provide list api feature to interact with blockchain node Using http server to provide a api service

Http client --(http request post)--> RPC http server <-----(json http response) --

  • Post body request:
{
    "jsonrpc": "1.0",
    "method": "__command_name__",
    "params": __json_data_format__,
    "id": __integer_number__
}
  • Response format:
{
    "Result": __json_data_format,
    "Error": {
        "code": __error_code__,
        "message": __error_message__,
    },
    "Id": __integer_number__
}
  • List common rpc command, client doesn't need to provide limited username/password to call:

    • getblockchaininfo
    • listtransactions
    • createrawtransaction
    • sendtransaction
    • getnumberofcoinsandbonds
    • createactionparamstransaction
    • votecandidate
    • getheader
  • List limited rpc command:

    • listaccounts
    • getaccount
    • getaddressesbyaccount
    • getaccountaddress
    • dumpprivkey
    • importaccount
    • listunspent

Documentation

Index

Constants

View Source
const (

	// reward
	CreateRawWithDrawTransaction                 = "withdrawreward"
	CreateRawWithDrawDelegationRewardTransaction = "withdrawdelegationreward"
)

rpc cmd method

View Source
const (
	RpcServerVersion = "1.0"
)

Variables

View Source
var BLogger = DeBridgeLogger{}
View Source
var (
	ErrParseTransaction = errors.New("Parse transaction failed")
)
View Source
var FeatureFlagWithMethodNames = map[string][]string{
	common.PortalRelayingFlag: {
		createAndSendTxWithRelayingBNBHeader,
		createAndSendTxWithRelayingBTCHeader,
		getRelayingBNBHeaderState,
		getRelayingBNBHeaderByBlockHeight,
		getBTCRelayingBestState,
		getBTCBlockByHash,
		getLatestBNBHeaderBlockHeight,
	},
	common.PortalV3Flag: {
		createAndSendTxWithCustodianDeposit,
		createAndSendTxWithReqPToken,
		getPortalState,
		getPortalCustodianDepositStatus,
		createAndSendRegisterPortingPublicTokens,
		createAndSendPortalExchangeRates,
		getPortalFinalExchangeRates,
		getPortalPortingRequestByKey,
		getPortalPortingRequestByPortingId,
		convertExchangeRates,
		getPortalReqPTokenStatus,
		getPortingRequestFees,
		createAndSendTxWithRedeemReq,
		createAndSendTxWithReqUnlockCollateral,
		getPortalReqUnlockCollateralStatus,
		getPortalReqRedeemStatus,
		createAndSendCustodianWithdrawRequest,
		getCustodianWithdrawByTxId,
		getCustodianLiquidationStatus,
		createAndSendTxWithReqWithdrawRewardPortal,
		createAndSendTxRedeemFromLiquidationPoolV3,
		createAndSendCustodianTopup,
		createAndSendTopUpWaitingPorting,
		createAndSendCustodianTopupV3,
		createAndSendTopUpWaitingPortingV3,
		getTopupAmountForCustodian,
		getLiquidationExchangeRatesPool,
		getPortalReward,
		getRequestWithdrawPortalRewardStatus,
		createAndSendTxWithReqMatchingRedeem,
		getReqMatchingRedeemStatus,
		getPortalCustodianTopupStatus,
		getPortalCustodianTopupStatusV3,
		getPortalCustodianTopupWaitingPortingStatus,
		getPortalCustodianTopupWaitingPortingStatusV3,
		getAmountTopUpWaitingPorting,
		getPortalReqRedeemByTxIDStatus,
		getReqRedeemFromLiquidationPoolByTxIDStatus,
		getReqRedeemFromLiquidationPoolByTxIDStatusV3,
		getPortalCustodianDepositStatusV3,
		checkPortalExternalHashSubmitted,
		createAndSendTxWithCustodianWithdrawRequestV3,
		getCustodianWithdrawRequestStatusV3ByTxId,
		getPortalWithdrawCollateralProof,
		createAndSendUnlockOverRateCollaterals,
		getPortalUnlockOverRateCollateralsStatus,
		getRewardFeature,
	},
	common.PortalV4Flag: {
		getPortalV4State,
		createAndSendTxWithShieldingRequest,
		getPortalShieldingRequestStatus,
		createAndSendTxWithPortalV4UnshieldRequest,
		getPortalUnshieldingRequestStatus,
		getPortalBatchUnshieldingRequestStatus,
		getSignedRawTransactionByBatchID,
		createAndSendTxWithPortalReplacementFee,
		getPortalReplacementFeeStatus,
		createAndSendTxWithPortalSubmitConfirmedTx,
		getPortalSubmitConfirmedTx,
		getSignedRawReplaceFeeTransaction,
		createAndSendTxPortalConvertVaultRequest,
		getPortalConvertVaultTxStatus,
		getPortalV4Params,
		generatePortalShieldMultisigAddress,
	},
}

add method names when add new feature flags

View Source
var HttpHandler = map[string]httpHandler{

	CreateRawWithDrawTransaction:                 (*HttpServer).handleCreateAndSendWithDrawTransaction,
	CreateRawWithDrawDelegationRewardTransaction: (*HttpServer).handleCreateAndSendWithdrawDelegationRewardTransaction,
	// contains filtered or unexported fields
}

Commands valid for normal user

View Source
var LimitedHttpHandler = map[string]httpHandler{
	// contains filtered or unexported fields
}

Commands that are available to a limited user

View Source
var Logger = RpcLogger{}

Global instant to use

View Source
var PrivacyCustomTokenCache, _ = lru.New(5000)

for fast retrieve token detail

View Source
var WsHandler = map[string]wsHandler{
	// contains filtered or unexported fields
}

Functions

func AddSubscription

func AddSubscription(subManager *SubcriptionManager, subRequest *SubcriptionRequest, closeChan chan struct{}) error

func AuthFail

func AuthFail(w http.ResponseWriter)

AuthFail sends a Message back to the client if the http auth is rejected.

func GenCertPair

func GenCertPair(certFile, keyFile string) error

genCertPair generates a key/cert pair to the paths provided.

func IsValidIDType

func IsValidIDType(id interface{}) bool

IsValidIDType checks that the Id field (which can go in any of the JSON-RPC requests, responses, or notifications) is valid. JSON-RPC 1.0 allows any valid JSON type. JSON-RPC 2.0 (which coind follows for some parts) only allows string, number, or null, so this function restricts the allowed types to that list. This function is only provided in case the caller is manually marshalling for some reason. The functions which accept an Id in this package already call this function to ensure the provided id is valid.

func NewCorsHeader

func NewCorsHeader(w http.ResponseWriter)

func NewTLSCertPair

func NewTLSCertPair(organization string, validUntil time.Time, extraHosts []string) (cert, key []byte, err error)

NewTLSCertPair returns a new PEM-encoded x.509 certificate pair based on a 521-bit ECDSA private key. The machine's local interface addresses and all variants of IPv4 and IPv6 localhost are included as valid IP addresses.

func RemoveSubcription

func RemoveSubcription(subManager *SubcriptionManager, subRequest *SubcriptionRequest) error

Types

type ConsensusEngine

type ConsensusEngine interface {
	ExtractBridgeValidationData(block types.BlockInterface) ([][]byte, []int, error)
	ExtractPortalV4ValidationData(block types.BlockInterface) ([]*portalprocessv4.PortalSig, error)
}

type ConvertedPrice

type ConvertedPrice struct {
	FromTokenIDStr string
	ToTokenIDStr   string
	Amount         uint64
	Price          uint64
}

type CountResult

type CountResult struct {
	Success int
	Fail    int
}

For testing and benchmark only

type DeBridgeLogger

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

func (*DeBridgeLogger) Init

func (self *DeBridgeLogger) Init(inst common.Logger)

type FileObject

type FileObject struct {
	Name string
	Size uint64
}

type HttpServer

type HttpServer struct {
	Pruner *pruner.PrunerManager
	// contains filtered or unexported fields
}

func (*HttpServer) DecrementClients

func (httpServer *HttpServer) DecrementClients()

DecrementClients subtracts one from the number of connected RPC clients. Note this only applies to standard clients.

This function is safe for concurrent access.

func (*HttpServer) GetBeaconChainDatabase

func (httpServer *HttpServer) GetBeaconChainDatabase() incdb.Database

func (*HttpServer) GetBlockchain

func (httpServer *HttpServer) GetBlockchain() *blockchain.BlockChain

func (*HttpServer) GetShardChainDatabase

func (httpServer *HttpServer) GetShardChainDatabase(shardID byte) incdb.Database

func (*HttpServer) IncrementClients

func (httpServer *HttpServer) IncrementClients()

IncrementClients adds one to the number of connected RPC clients. Note this only applies to standard clients.

This function is safe for concurrent access.

func (*HttpServer) Init

func (httpServer *HttpServer) Init(config *RpcServerConfig)

func (*HttpServer) ProcessRpcRequest

func (httpServer *HttpServer) ProcessRpcRequest(w http.ResponseWriter, r *http.Request, isLimitedUser bool)

func (*HttpServer) Start

func (httpServer *HttpServer) Start() error

Start is used by rpcserver.go to start the rpc listener.

func (*HttpServer) Stop

func (httpServer *HttpServer) Stop()

Stop is used by rpcserver.go to stop the rpc listener.

type JsonRequest

type JsonRequest struct {
	Jsonrpc string      `json:"Jsonrpc"`
	Method  string      `json:"Method"`
	Params  interface{} `json:"Params"`
	Id      interface{} `json:"Id"`
}

The JSON-RPC 1.0 spec defines that notifications must have their "id" set to null and states that notifications do not have a response.

A JSON-RPC 2.0 notification is a request with "json-rpc":"2.0", and without an "id" member. The specification states that notifications must not be responded to. JSON-RPC 2.0 permits the null value as a valid request id, therefore such requests are not notifications.

coin Core serves requests with "id":null or even an absent "id", and responds to such requests with "id":null in the response.

Rpc does not respond to any request without and "id" or "id":null, regardless the indicated JSON-RPC protocol version unless RPC quirks are enabled. With RPC quirks enabled, such requests will be responded to if the reqeust does not indicate JSON-RPC version.

RPC quirks can be enabled by the user to avoid compatibility issues with software relying on Core's behavior.

type JsonResponse

type JsonResponse struct {
	Id      *interface{}         `json:"Id"`
	Result  json.RawMessage      `json:"Result"`
	Error   *rpcservice.RPCError `json:"Error"`
	Params  interface{}          `json:"Params"`
	Method  string               `json:"Method"`
	Jsonrpc string               `json:"Jsonrpc"`
}

JsonResponse is the general form of a JSON-RPC response. The type of the Result field varies from one command to the next, so it is implemented as an interface. The Id field has to be a pointer for Go to put a null in it when empty.

type PDEAcceptedTradeV2

type PDEAcceptedTradeV2 struct {
	TraderAddressStr string
	ShardID          byte
	RequestedTxID    common.Hash
	Status           string
	BeaconHeight     uint64
	TradePaths       []TradePath
}

type PDEContribution

type PDEContribution struct {
	PDEContributionPairID string
	ContributorAddressStr string
	ContributedAmount     uint64
	TokenIDStr            string
	TxReqID               common.Hash
	ShardID               byte
	Status                string
	BeaconHeight          uint64
}

type PDEInfoFromBeaconBlock

type PDEInfoFromBeaconBlock struct {
	PDEContributions    []*PDEContribution    `json:"PDEContributions"`
	PDETrades           []*PDETrade           `json:"PDETrades"`
	PDEWithdrawals      []*PDEWithdrawal      `json:"PDEWithdrawals"`
	PDEAcceptedTradesV2 []*PDEAcceptedTradeV2 `json:"PDEAcceptedTradesV2"`
	PDERefundedTradesV2 []*PDERefundedTradeV2 `json:"PDERefundedTradesV2"`
	BeaconTimeStamp     int64                 `json:"BeaconTimeStamp"`
}

type PDERefundedTradeV2

type PDERefundedTradeV2 struct {
	TraderAddressStr string
	TokenIDStr       string
	ReceiveAmount    uint64
	ShardID          byte
	RequestedTxID    common.Hash
	Status           string
	BeaconHeight     uint64
}

type PDETrade

type PDETrade struct {
	TraderAddressStr    string
	ReceivingTokenIDStr string
	ReceiveAmount       uint64
	Token1IDStr         string
	Token2IDStr         string
	ShardID             byte
	RequestedTxID       common.Hash
	Status              string
	BeaconHeight        uint64
}

type PDEWithdrawal

type PDEWithdrawal struct {
	WithdrawalTokenIDStr string
	WithdrawerAddressStr string
	DeductingPoolValue   uint64
	DeductingShares      uint64
	PairToken1IDStr      string
	PairToken2IDStr      string
	TxReqID              common.Hash
	ShardID              byte
	Status               string
	BeaconHeight         uint64
}

type Result

type Result struct {
	Result      interface{}
	Subcription string
}

type RpcLogger

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

func (*RpcLogger) Init

func (rpcLogger *RpcLogger) Init(inst common.Logger)

type RpcServer

type RpcServer struct {
	HttpServer *HttpServer
	WsServer   *WsServer

	RpcServer *http.Server
	// contains filtered or unexported fields
}

rpcServer provides a concurrent safe RPC server to a chain server.

func (*RpcServer) Init

func (rpcServer *RpcServer) Init(config *RpcServerConfig)

func (*RpcServer) RequestedProcessShutdown

func (rpcServer *RpcServer) RequestedProcessShutdown() <-chan struct{}

RequestedProcessShutdown returns a channel that is sent to when an authorized RPC client requests the process to shutdown. If the request can not be read immediately, it is dropped.

func (*RpcServer) Start

func (rpcServer *RpcServer) Start()

func (*RpcServer) Stop

func (rpcServer *RpcServer) Stop()

type RpcServerConfig

type RpcServerConfig struct {
	HttpListenters  []net.Listener
	WsListenters    []net.Listener
	ProtocolVersion string
	BlockChain      *blockchain.BlockChain
	Blockgen        *blockchain.BlockGenerator
	MemCache        *memcache.MemoryCache
	Database        map[int]incdb.Database
	Wallet          *wallet.Wallet
	ConnMgr         *connmanager.ConnManager
	AddrMgr         *addrmanager.AddrManager
	// NodeMode        string
	NetSync *netsync.NetSync
	Syncker *syncker.SynckerManager
	Server  interface {
		// Push TxNormal Message
		PushMessageToAll(message wire.Message) error
		PushMessageToShard(msg wire.Message, shard byte) error
		PushMessageToPeer(message wire.Message, id peer2.ID) error
		GetNodeRole() string
		// GetUserKeySet() *incognitokey.KeySet
		EnableMining(enable bool) error
		IsEnableMining() bool
		GetChainMiningStatus(chain int) string
		GetPublicKeyRole(publicKey string, keyType string) (int, int)
		GetIncognitoPublicKeyRole(publicKey string) (int, bool, int)
		GetMinerIncognitoPublickey(publicKey string, keyType string) []byte
		OnTx(p *peer.PeerConn, msg *wire.MessageTx)
		OnTxPrivacyToken(p *peer.PeerConn, msg *wire.MessageTxPrivacyToken)
	}

	ConsensusEngine blockchain.ConsensusEngine

	TxMemPool                   rpcservice.MempoolInterface
	RPCMaxClients               int
	RPCMaxWSClients             int
	RPCLimitRequestPerDay       int
	RPCLimitRequestErrorPerHour int
	RPCQuirks                   bool
	// Authentication
	RPCUser      string
	RPCPass      string
	RPCLimitUser string
	RPCLimitPass string
	DisableAuth  bool
	// The fee estimator keeps track of how long transactions are left in
	// the mempool before they are mined into blocks.
	FeeEstimator map[byte]*mempool.FeeEstimator
	// IsMiningNode    bool   // flag mining node. True: mining, False: not mining
	MiningKeys    string // encode of mining key
	PubSubManager *pubsub.PubSubManager
	Pruner        *pruner.PrunerManager
}

type RpcSubResult

type RpcSubResult struct {
	Result interface{}
	Error  *rpcservice.RPCError
}

type SubcriptionManager

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

Manage All Subcription from one socket connection

func NewSubscriptionManager

func NewSubscriptionManager(ws *websocket.Conn) *SubcriptionManager

type SubcriptionRequest

type SubcriptionRequest struct {
	JsonRequest JsonRequest `json:"Request"`
	Subcription string      `json:"Subcription"`
	Type        int         `json:"Type"`
}

type for subcribe and unsubcribe 0: subcribe 1: unsubcribe

type SubcriptionResult

type SubcriptionResult struct {
	Subscription string          `json:"Subscription"`
	Result       json.RawMessage `json:"Result"`
}

type TokenInitParam

type TokenInitParam struct {
	PrivateKey  string `json:"PrivateKey"`
	TokenName   string `json:"TokenName"`
	TokenSymbol string `json:"TokenSymbol"`
	Amount      uint64 `json:"Amount"`
}

type TradePath

type TradePath struct {
	TokenIDToBuyStr string
	ReceiveAmount   uint64
	SellAmount      uint64
	Token1IDStr     string
	Token2IDStr     string
}

type Uint64Reader

type Uint64Reader uint64

Uint64Reader wraps the unmarshaling of uint64 numbers from both integer & string formats.

func (Uint64Reader) MarshalJSON

func (u Uint64Reader) MarshalJSON() ([]byte, error)

func (*Uint64Reader) UnmarshalJSON

func (u *Uint64Reader) UnmarshalJSON(raw []byte) error

type UsageFlag

type UsageFlag uint32

UsageFlag define flags that specify additional properties about the circumstances under which a command can be used.

type WsServer

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

func (*WsServer) DecrementWsClients

func (wsServer *WsServer) DecrementWsClients()

func (*WsServer) GetBlockchain

func (wsServer *WsServer) GetBlockchain() *blockchain.BlockChain

func (*WsServer) IncrementWsClients

func (wsServer *WsServer) IncrementWsClients()

func (*WsServer) Init

func (wsServer *WsServer) Init(config *RpcServerConfig)

func (*WsServer) ProcessRpcWsRequest

func (wsServer *WsServer) ProcessRpcWsRequest(ws *websocket.Conn)

func (*WsServer) Start

func (wsServer *WsServer) Start() error

Start is used by rpcserver.go to start the rpc listener.

func (*WsServer) Stop

func (wsServer *WsServer) Stop()

Stop is used by rpcserver.go to stop the rpc listener.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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