log "github.com/sirupsen/logrus"
cmn "github.com/tendermint/tmlibs/common"
- "github.com/bytom/accesstoken"
- "github.com/bytom/blockchain/txfeed"
- cfg "github.com/bytom/config"
- "github.com/bytom/dashboard"
- "github.com/bytom/errors"
- "github.com/bytom/mining/cpuminer"
- "github.com/bytom/mining/miningpool"
- "github.com/bytom/net/http/authn"
- "github.com/bytom/net/http/gzip"
- "github.com/bytom/net/http/httpjson"
- "github.com/bytom/net/http/static"
- "github.com/bytom/netsync"
- "github.com/bytom/protocol"
- "github.com/bytom/wallet"
+ "github.com/bytom/bytom/accesstoken"
+ "github.com/bytom/bytom/blockchain/txfeed"
+ cfg "github.com/bytom/bytom/config"
+ "github.com/bytom/bytom/dashboard/dashboard"
+ "github.com/bytom/bytom/dashboard/equity"
+ "github.com/bytom/bytom/errors"
+ "github.com/bytom/bytom/event"
+ "github.com/bytom/bytom/mining/cpuminer"
+ "github.com/bytom/bytom/mining/miningpool"
+ "github.com/bytom/bytom/net/http/authn"
+ "github.com/bytom/bytom/net/http/gzip"
+ "github.com/bytom/bytom/net/http/httpjson"
+ "github.com/bytom/bytom/net/http/static"
+ "github.com/bytom/bytom/net/websocket"
+ "github.com/bytom/bytom/netsync"
+ "github.com/bytom/bytom/p2p"
+ "github.com/bytom/bytom/protocol"
+ "github.com/bytom/bytom/wallet"
)
var (
// SUCCESS indicates the rpc calling is successful.
SUCCESS = "success"
// FAIL indicated the rpc calling is failed.
- FAIL = "fail"
- crosscoreRPCPrefix = "/rpc/"
+ FAIL = "fail"
+ logModule = "api"
)
// Response describes the response standard.
if info, ok := respErrFormatter[root]; ok {
response.Code = info.ChainCode
response.Msg = info.Message
- response.ErrorDetail = errors.Detail(err)
+ response.ErrorDetail = err.Error()
+ } else {
+ response.Code = respErrFormatter[ErrDefault].ChainCode
+ response.Msg = respErrFormatter[ErrDefault].Message
+ response.ErrorDetail = err.Error()
}
return response
}
//NewErrorResponse error response
func NewErrorResponse(err error) Response {
response := FormatErrResp(err)
- if response.Msg == "" {
- response.Msg = err.Error()
- }
return response
}
// API is the scheduling center for server
type API struct {
- sync *netsync.SyncManager
- wallet *wallet.Wallet
- accessTokens *accesstoken.CredentialStore
- chain *protocol.Chain
- server *http.Server
- handler http.Handler
- txFeedTracker *txfeed.Tracker
- cpuMiner *cpuminer.CPUMiner
- miningPool *miningpool.MiningPool
+ sync NetSync
+ wallet *wallet.Wallet
+ accessTokens *accesstoken.CredentialStore
+ chain *protocol.Chain
+ server *http.Server
+ handler http.Handler
+ txFeedTracker *txfeed.Tracker
+ cpuMiner *cpuminer.CPUMiner
+ miningPool *miningpool.MiningPool
+ notificationMgr *websocket.WSNotificationManager
+ eventDispatcher *event.Dispatcher
}
func (a *API) initServer(config *cfg.Config) {
mux := http.NewServeMux()
mux.Handle("/", &coreHandler)
- handler = mux
- if config.Auth.Disable == false {
- handler = AuthHandler(handler, a.accessTokens)
- }
+ handler = AuthHandler(mux, a.accessTokens, config.Auth.Disable)
handler = RedirectHandler(handler)
secureheader.DefaultConfig.PermitClearLoopback = true
// StartServer start the server
func (a *API) StartServer(address string) {
- log.WithField("api address:", address).Info("Rpc listen")
+ log.WithFields(log.Fields{"module": logModule, "api address:": address}).Info("Rpc listen")
listener, err := net.Listen("tcp", address)
if err != nil {
cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
// we call it.
go func() {
if err := a.server.Serve(listener); err != nil {
- log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
+ log.WithFields(log.Fields{"module": logModule, "error": errors.Wrap(err, "Serve")}).Error("Rpc server")
}
}()
}
+type NetSync interface {
+ IsListening() bool
+ IsCaughtUp() bool
+ PeerCount() int
+ GetNetwork() string
+ BestPeer() *netsync.PeerInfo
+ DialPeerWithAddress(addr *p2p.NetAddress) error
+ GetPeerInfos() []*netsync.PeerInfo
+ StopPeer(peerID string) error
+}
+
// NewAPI create and initialize the API
-func NewAPI(sync *netsync.SyncManager, wallet *wallet.Wallet, txfeeds *txfeed.Tracker, cpuMiner *cpuminer.CPUMiner, miningPool *miningpool.MiningPool, chain *protocol.Chain, config *cfg.Config, token *accesstoken.CredentialStore) *API {
+func NewAPI(sync NetSync, wallet *wallet.Wallet, txfeeds *txfeed.Tracker, cpuMiner *cpuminer.CPUMiner, miningPool *miningpool.MiningPool, chain *protocol.Chain, config *cfg.Config, token *accesstoken.CredentialStore, dispatcher *event.Dispatcher, notificationMgr *websocket.WSNotificationManager) *API {
api := &API{
sync: sync,
wallet: wallet,
txFeedTracker: txfeeds,
cpuMiner: cpuMiner,
miningPool: miningPool,
+
+ eventDispatcher: dispatcher,
+ notificationMgr: notificationMgr,
}
api.buildHandler()
api.initServer(config)
m := http.NewServeMux()
if a.wallet != nil {
walletEnable = true
-
m.Handle("/create-account", jsonHandler(a.createAccount))
+ m.Handle("/update-account-alias", jsonHandler(a.updateAccountAlias))
m.Handle("/list-accounts", jsonHandler(a.listAccounts))
m.Handle("/delete-account", jsonHandler(a.deleteAccount))
m.Handle("/validate-address", jsonHandler(a.validateAddress))
m.Handle("/list-pubkeys", jsonHandler(a.listPubKeys))
+ m.Handle("/get-mining-address", jsonHandler(a.getMiningAddress))
+ m.Handle("/set-mining-address", jsonHandler(a.setMiningAddress))
+
+ m.Handle("/get-coinbase-arbitrary", jsonHandler(a.getCoinbaseArbitrary))
+ m.Handle("/set-coinbase-arbitrary", jsonHandler(a.setCoinbaseArbitrary))
+
m.Handle("/create-asset", jsonHandler(a.createAsset))
m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
m.Handle("/get-asset", jsonHandler(a.getAsset))
m.Handle("/list-assets", jsonHandler(a.listAssets))
m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
+ m.Handle("/update-key-alias", jsonHandler(a.pseudohsmUpdateKeyAlias))
m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
+ m.Handle("/check-key-password", jsonHandler(a.pseudohsmCheckPassword))
m.Handle("/sign-message", jsonHandler(a.signMessage))
m.Handle("/build-transaction", jsonHandler(a.build))
- m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
+ m.Handle("/build-chain-transactions", jsonHandler(a.buildChainTxs))
+ m.Handle("/sign-transaction", jsonHandler(a.signTemplate))
+ m.Handle("/sign-transactions", jsonHandler(a.signTemplates))
m.Handle("/get-transaction", jsonHandler(a.getTransaction))
m.Handle("/list-transactions", jsonHandler(a.listTransactions))
m.Handle("/list-balances", jsonHandler(a.listBalances))
m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
+ m.Handle("/decode-program", jsonHandler(a.decodeProgram))
+
m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
m.Handle("/rescan-wallet", jsonHandler(a.rescanWallet))
m.Handle("/wallet-info", jsonHandler(a.getWalletInfo))
+ m.Handle("/recovery-wallet", jsonHandler(a.recoveryFromRootXPubs))
} else {
log.Warn("Please enable wallet")
}
m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
m.Handle("/submit-transaction", jsonHandler(a.submit))
+ m.Handle("/submit-transactions", jsonHandler(a.submitTxs))
m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
+ m.Handle("/estimate-chain-transaction-gas", jsonHandler(a.estimateChainTxGas))
m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
+ m.Handle("/get-block", jsonHandler(a.getBlock))
+ m.Handle("/get-raw-block", jsonHandler(a.getRawBlock))
m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
- m.Handle("/get-block", jsonHandler(a.getBlock))
m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
m.Handle("/get-work", jsonHandler(a.getWork))
m.Handle("/get-work-json", jsonHandler(a.getWorkJSON))
+ m.Handle("/submit-block", jsonHandler(a.submitBlock))
m.Handle("/submit-work", jsonHandler(a.submitWork))
m.Handle("/submit-work-json", jsonHandler(a.submitWorkJSON))
m.Handle("/verify-message", jsonHandler(a.verifyMessage))
- m.Handle("/decode-program", jsonHandler(a.decodeProgram))
+ m.Handle("/compile", jsonHandler(a.compileEquity))
m.Handle("/gas-rate", jsonHandler(a.gasRate))
m.Handle("/net-info", jsonHandler(a.getNetInfo))
- handler := latencyHandler(m, walletEnable)
- handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
+ m.Handle("/list-peers", jsonHandler(a.listPeers))
+ m.Handle("/disconnect-peer", jsonHandler(a.disconnectPeer))
+ m.Handle("/connect-peer", jsonHandler(a.connectPeer))
+
+ m.Handle("/get-merkle-proof", jsonHandler(a.getMerkleProof))
+
+ m.HandleFunc("/websocket-subscribe", a.websocketHandler)
+
+ handler := walletHandler(m, walletEnable)
handler = webAssetsHandler(handler)
handler = gzip.Handler{Handler: handler}
-
a.handler = handler
}
-func maxBytesHandler(h http.Handler) http.Handler {
- const maxReqSize = 1e7 // 10MB
- return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- // A block can easily be bigger than maxReqSize, but everything
- // else should be pretty small.
- if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
- req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
- }
- h.ServeHTTP(w, req)
- })
-}
-
// json Handler
func jsonHandler(f interface{}) http.Handler {
h, err := httpjson.Handler(f, errorFormatter.Write)
Assets: dashboard.Files,
Default: "index.html",
}))
+ mux.Handle("/equity/", http.StripPrefix("/equity/", static.Handler{
+ Assets: equity.Files,
+ Default: "index.html",
+ }))
mux.Handle("/", next)
return mux
}
// AuthHandler access token auth Handler
-func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
- authenticator := authn.NewAPI(accessTokens)
+func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore, authDisable bool) http.Handler {
+ authenticator := authn.NewAPI(accessTokens, authDisable)
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// TODO(tessr): check that this path exists; return early if this path isn't legit
req, err := authenticator.Authenticate(req)
if err != nil {
- log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
- err = errors.Sub(errNotAuthenticated, err)
+ log.WithFields(log.Fields{"module": logModule, "error": errors.Wrap(err, "Serve")}).Error("Authenticate fail")
+ err = errors.WithDetail(errNotAuthenticated, err.Error())
errorFormatter.Write(req.Context(), rw, err)
return
}
})
}
-// latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
-func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
+func walletHandler(m *http.ServeMux, walletEnable bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- // latency for the request url path
- if l := latency(m, req); l != nil {
- defer l.RecordSince(time.Now())
- }
-
// when the wallet is not been opened and the url path is not been found, modify url path to error,
// and redirect handler to error
if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {