OSDN Git Service

ADD hsm handler
authorjianyixun <317316abcd@163.com>
Fri, 22 Sep 2017 06:26:30 +0000 (14:26 +0800)
committerjianyixun <317316abcd@163.com>
Fri, 22 Sep 2017 06:26:30 +0000 (14:26 +0800)
add hsm into BlockchainReasctor
add nodekey dir

13 files changed:
blockchain/hsm.go
blockchain/pseudohsm/addrcache.go
blockchain/pseudohsm/addrcache_test.go
blockchain/pseudohsm/key.go
blockchain/pseudohsm/keystore_passphrase.go
blockchain/pseudohsm/keystore_passphrase_test.go
blockchain/pseudohsm/pseudohsm.go
blockchain/pseudohsm/pseudohsm_test.go
blockchain/reactor.go
cmd/bytom/pseudohsm.go [deleted file]
cmd/bytom/remotehsm.go [deleted file]
config/config.go
node/node.go

index 1aff0aa..a3928f9 100644 (file)
@@ -4,11 +4,11 @@ package core
 
 import (
        "context"
-       "bytom/core/pseudohsm"
-       "bytom/core/txbuilder"
-       "bytom/crypto/ed25519/chainkd"
-       "bytom/net/http/httperror"
-       "bytom/net/http/httpjson"
+       "github.com/bytom/blockchain/pseudohsm"
+       "github.com/bytom/blockchain/txbuilder"
+       "github.com/bytom/crypto/ed25519/chainkd"
+       "github.com/bytom/net/http/httperror"
+       "github.com/bytom/net/http/httpjson"
 )
 
 func init() {
@@ -19,6 +19,7 @@ func init() {
 
 // PseudoHSM configures the Core to expose the PseudoHSM endpoints. It
 // is only included in non-production builds.
+/*
 func PseudoHSM(hsm *Pseudohsm.HSM) RunOption {
        return func(api *API) {
 
@@ -37,13 +38,14 @@ func PseudoHSM(hsm *Pseudohsm.HSM) RunOption {
 type pseudoHSMHandler struct {
        PseudoHSM *Pseudohsm.HSM
 }
+*/
 
 
-func (h *PseudoHSMHandler) pseudohsmCreateKey(ctx context.Context, password string, in struct{ Alias string }) (result *Pseudohsm.XPub, err error) {
-       return h.PseudoHSM.XCreate(password, in.Alias)
+func (a *BlockchainReactor) pseudohsmCreateKey(ctx context.Context, password string, in struct{ Alias string }) (result *Pseudohsm.XPub, err error) {
+       return a.hsm.XCreate(password, in.Alias)
 }
 
-func (h *PseudoHSMHandler) pseudohsmListKeys(ctx context.Context, query requestQuery) (page, error) {
+func (a *BlockchainReactor)) pseudohsmListKeys(ctx context.Context, query requestQuery) (page, error) {
        limit := query.PageSize
        if limit == 0 {
                limit = defGenericPageSize  // defGenericPageSize = 100
@@ -68,20 +70,20 @@ func (h *PseudoHSMHandler) pseudohsmListKeys(ctx context.Context, query requestQ
        }, nil
 }
 
-func (h *PseudoHSMHandler) pseudohsmDeleteKey(ctx context.Context, xpub chainkd.XPub, password string) error {
-       return h.PseudoHSM.XDelete(xpub, password)
+func (a *BlockchainReactor) pseudohsmDeleteKey(ctx context.Context, xpub chainkd.XPub, password string) error {
+       return a.hsm.XDelete(xpub, password)
 }
 
-func (h *PseudoHSMHandler) pseudohsmSignTemplates(ctx context.Context, x struct {
+func (a *BlockchainReactor) pseudohsmSignTemplates(ctx context.Context, x struct {
        Txs   []*txbuilder.Template `json:"transactions"`
        XPubs []chainkd.XPub        `json:"xpubs"`
 }) []interface{} {
        resp := make([]interface{}, 0, len(x.Txs))
        for _, tx := range x.Txs {
-               err := txbuilder.Sign(ctx, tx, x.XPubs, h.pseudohsmSignTemplate)
+               err := txbuilder.Sign(ctx, tx, x.XPubs, a.hsm.pseudohsmSignTemplate)
                if err != nil {
                        info := errorFormatter.Format(err)
-                       resp = append(resp, info)
+                       response = append(resp, info)
                } else {
                        resp = append(resp, tx)
                }
@@ -89,8 +91,8 @@ func (h *PseudoHSMHandler) pseudohsmSignTemplates(ctx context.Context, x struct
        return resp
 }
 
-func (h *PseudoHSMHandler) pseudohsmSignTemplate(ctx context.Context, xpub chainkd.XPub, path [][]byte, data [32]byte) ([]byte, error) {
-       sigBytes, err := h.PseudoHSM.XSign(ctx, xpub, path, data[:])
+func (a *BlockchainReactor) pseudohsmSignTemplate(ctx context.Context, xpub chainkd.XPub, path [][]byte, data [32]byte) ([]byte, error) {
+       sigBytes, err := a.hsm.XSign(ctx, xpub, path, data[:])
        if err == Pseudohsm.ErrNoKey {
                return nil, nil
        }
@@ -98,7 +100,7 @@ func (h *PseudoHSMHandler) pseudohsmSignTemplate(ctx context.Context, xpub chain
 }
 
 // remote hsm used
-
+/*
 func RemoteHSM(hsm *remoteHSM) RunOption {
        return func(api *API) {
                h := &retmoteHSMHandler{RemoteHSM: hsm}
@@ -107,7 +109,7 @@ func RemoteHSM(hsm *remoteHSM) RunOption {
        }
 }
 
-/*
+
 type remoteHSM struct {
        Client *rpc.Client
 }
index 60e6b8c..12e3064 100644 (file)
@@ -28,8 +28,8 @@ import (
        "sync"
        "time"
 
-       "bytom/common"
-       _"bytom/errors"
+       "github.com/bytom/common"
+       _"github.com/bytom/errors"
 )
 
 // Minimum amount of time between cache reloads. This limit applies if the platform does
index 024631b..804b4cd 100644 (file)
@@ -27,7 +27,7 @@ import (
        "testing"
        "time"
 
-       "bytom/common"
+       "github.com/bytom/common"
        "github.com/cespare/cp"
        "github.com/davecgh/go-spew/spew"
 )
index 42b47d1..bc71f2b 100644 (file)
@@ -9,8 +9,8 @@ import (
        "path/filepath"
        "time"
 
-       "bytom/common"
-       "bytom/crypto/ed25519/chainkd"
+       "github.com/bytom/common"
+       "github.com/bytom/crypto/ed25519/chainkd"
 
        "github.com/pborman/uuid"
 
index 9faead1..7d5e444 100644 (file)
@@ -36,10 +36,10 @@ import (
        "io/ioutil"
        "path/filepath"
 
-       "bytom/common"
-       "bytom/crypto"
-       "bytom/crypto/randentropy"
-       "bytom/crypto/ed25519/chainkd"
+       "github.com/bytom/common"
+       "github.com/bytom/crypto"
+       "github.com/bytom/crypto/randentropy"
+       "github.com/bytom/crypto/ed25519/chainkd"
        "github.com/pborman/uuid"
        "golang.org/x/crypto/pbkdf2"
        "golang.org/x/crypto/scrypt"
index 5449dfd..f6cd7aa 100644 (file)
@@ -20,9 +20,9 @@ import (
        "io/ioutil"
        "testing"
 
-       "bytom/common"
-       "bytom/crypto"
-       "bytom/crypto/ed25519/chainkd"
+       "github.com/bytom/common"
+       "github.com/bytom/crypto"
+       "github.com/bytom/crypto/ed25519/chainkd"
 
        "github.com/pborman/uuid"
 
index e95b7d3..e0e1b08 100644 (file)
@@ -9,13 +9,12 @@ import (
        "sync"
        "os"
 
-       "bytom/crypto/ed25519/chainkd"
-       "bytom/common"
-       "bytom/errors"
-       "bytom/crypto"
+       "github.com/bytom/crypto/ed25519/chainkd"
+       "github.com/bytom/common"
+       "github.com/bytom/errors"
+       "github.com/bytom/crypto"
        //"bytom/protocol/bc/legacy"
-
-       "bytom/blockchain/config"
+       "github.com/bytom/blockchain/config"
        "github.com/pborman/uuid"
 )
 
@@ -46,13 +45,13 @@ type XPub struct {
        File    string             `json:"file"`
 }
 
-func New(conf *config.Config) *HSM {
-       keydir, _ := filepath.Abs(conf.KeyPath)
+func New(keypath string) (*HSM, error) {
+       keydir, _ := filepath.Abs(keypath)
        return &HSM{
                keyStore:   &keyStorePassphrase{keydir, LightScryptN, LightScryptP},
                cache:          newAddrCache(keydir),
                kdCache:        make(map[chainkd.XPub]chainkd.XPrv),
-       }
+       }, nil
 }
 
 // XCreate produces a new random xprv and stores it in the db.
index 111193f..a2aec04 100644 (file)
@@ -5,8 +5,8 @@ import (
        "testing"
        _"github.com/davecgh/go-spew/spew"
 
-       "bytom/blockchain/config"
-       "bytom/errors"
+       "github.com/bytom/blockchain/config"
+       "github.com/bytom/errors"
        //"bytom/protocol/bc/legacy"
 )
 
index 65c51ac..8567c28 100644 (file)
@@ -23,6 +23,7 @@ import (
        "github.com/bytom/types"
        wire "github.com/tendermint/go-wire"
        cmn "github.com/tendermint/tmlibs/common"
+       "github.com/bytom/crypto/ed25519/chainkd"
        //"github.com/bytom/net/http/gzip"
        "github.com/bytom/net/http/httpjson"
        //"github.com/bytom/net/http/limit"
@@ -51,6 +52,10 @@ const (
        crosscoreRPCPrefix               = "/rpc/"
 )
 
+type hsmSigner interface {
+       XSign(ctx context.Context, xpub chainkd.XPub, path [][]byte, msg []byte) ([]byte, error)
+}
+
 // BlockchainReactor handles long-term catchup syncing.
 type BlockchainReactor struct {
        p2p.BaseReactor
@@ -69,6 +74,7 @@ type BlockchainReactor struct {
        requestsCh chan BlockRequest
        timeoutsCh chan string
        submitter  txbuilder.Submitter
+       hsm                     hsmSigner
        chain       *protocol.Chain
        store       *txdb.Store
        accounts    *account.Manager
@@ -77,7 +83,7 @@ type BlockchainReactor struct {
        pool        *BlockPool
        mux         *http.ServeMux
        accesstoken *accesstoken.Token
-       handler     http.Handler
+
        fastSync    bool
        requestsCh  chan BlockRequest
        timeoutsCh  chan string
@@ -108,6 +114,8 @@ func batchRecover(ctx context.Context, v *interface{}) {
        }
 }
 
+
+
 func jsonHandler(f interface{}) http.Handler {
        h, err := httpjson.Handler(f, errorFormatter.Write)
        if err != nil {
@@ -120,6 +128,7 @@ func alwaysError(err error) http.Handler {
        return jsonHandler(func() error { return err })
 }
 
+
 func (bcr *BlockchainReactor) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
        bcr.handler.ServeHTTP(rw, req)
 }
@@ -191,6 +200,14 @@ func (bcr *BlockchainReactor) BuildHander() {
        m.Handle("/list-access-tokens", jsonHandler(bcr.listAccessTokens))
        m.Handle("/delete-access-token", jsonHandler(bcr.deleteAccessToken))
 
+       m.Handle("/hsm/create-key", needConfig(bcr.pseudohsmCreateKey))
+       m.Handle("/hsm/list-keys", needConfig(bcr.pseudohsmListKeys))
+       m.Handle("/hsm/delete-key", needConfig(bcr.pseudohsmDeleteKey))
+       m.Handle("/hsm/sign-transaction", needConfig(bcr.pseudohsmSignTemplates))
+       m.Handle("/hsm/reset-password", needConfig(bcr.pseudohsmResetPassword))
+       m.Handle("/hsm/update-alias", needConfig(bcr.pseudohsmUpdateAlias))
+
+
        latencyHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
                if l := latency(m, req); l != nil {
                        defer l.RecordSince(time.Now())
@@ -210,6 +227,7 @@ func (bcr *BlockchainReactor) BuildHander() {
                        handler = blockchainIDHandler(handler, a.config.BlockchainId.String())
                }
        */
+
        bcr.handler = handler
 }
 
@@ -253,7 +271,7 @@ type page struct {
        LastPage bool         `json:"last_page"`
 }
 
-func NewBlockchainReactor(store *txdb.Store, chain *protocol.Chain, accounts *account.Manager, assets *asset.Registry, fastSync bool) *BlockchainReactor {
+func NewBlockchainReactor(store *txdb.Store, chain *protocol.Chain, accounts *account.Manager, assets *asset.Registry, hsm hsmSigner, fastSync bool) *BlockchainReactor {
        requestsCh := make(chan BlockRequest, defaultChannelCapacity)
        timeoutsCh := make(chan string, defaultChannelCapacity)
        pool := NewBlockPool(
@@ -271,6 +289,7 @@ func NewBlockchainReactor(store *txdb.Store, chain *protocol.Chain, accounts *ac
                txPool:     txPool,
                mining:     mining,
                mux:        http.NewServeMux(),
+               hsm:            hsm,
                fastSync:   fastSync,
                requestsCh: requestsCh,
                timeoutsCh: timeoutsCh,
diff --git a/cmd/bytom/pseudohsm.go b/cmd/bytom/pseudohsm.go
deleted file mode 100644 (file)
index c349cee..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-//+build pseudohsm
-
-package main
-
-import (
-       "bytom/core"
-       "bytom/core/config"
-       "bytom/core/pseduokhsm"
-)
-
-func init() {
-       config.BuildConfig.PseudoHSM = true
-}
-
-func enablePseudoHSM(config *config.Config) []core.RunOption {
-       return []core.RunOption{core.PseudoHSM(Pseudohsm.New(config))}
-}
diff --git a/cmd/bytom/remotehsm.go b/cmd/bytom/remotehsm.go
deleted file mode 100644 (file)
index 21e3947..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-//+build remotehsm
-
-package main
-
-import (
-       "bytom/core"
-       "bytom/core/config"
-)
-
-func init() {
-       config.BuildConfig.PseudoHSM = false
-}
-
-func enableHSM(config *config.Config) []core.RunOption {
-       return []core.RunOption{core.RemoteHSM(Remotehsm.New(config))}
-}
index 351e778..a259a77 100644 (file)
@@ -83,6 +83,12 @@ type BaseConfig struct {
        // Database directory
        DBPath string `mapstructure:"db_dir"`
 
+       // Keystore directory
+       KeysPath string `mapstructure:"keys_dir"`
+
+       // remote HSM url
+       HsmUrl string `mapstructure:"hsm_url"`
+
        ApiAddress string `mapstructure:"api_addr"`
 
        Time time.Time
@@ -99,6 +105,8 @@ func DefaultBaseConfig() BaseConfig {
                TxIndex:           "kv",
                DBBackend:         "leveldb",
                DBPath:            "data",
+               KeysPath:                  "keystore",
+               HsmUrl:                    ""
        }
 }
 
@@ -118,6 +126,11 @@ func (b BaseConfig) DBDir() string {
        return rootify(b.DBPath, b.RootDir)
 }
 
+func (b BaseConfig) KeysDir() string {
+       return rootify(b.KeysPath, b.RootDir)
+}
+
+
 func DefaultLogLevel() string {
        return "info"
 }
index d36f8fb..14b4426 100644 (file)
@@ -27,6 +27,7 @@ import (
        "github.com/bytom/blockchain/account"
        "github.com/bytom/blockchain/asset"
        "github.com/bytom/blockchain/txdb"
+       "github.com/bytom/blockchain/pseudohsm"
        "github.com/bytom/net/http/reqid"
        "github.com/bytom/protocol"
        rpcserver "github.com/bytom/rpc/lib/server"
@@ -214,7 +215,21 @@ func NewNode(config *cfg.Config, logger log.Logger) *Node {
        accounts := account.NewManager(accounts_db, chain)
        assets_db := dbm.NewDB("asset", config.DBBackend, config.DBDir())
        assets := asset.NewRegistry(assets_db, chain)
-       bcReactor := bc.NewBlockchainReactor(store, chain, txPool, accounts, assets, fastSync)
+
+       //Todo HSM
+       var hsm bc.hsmSigner
+
+       if config.HsmUrl != ""{
+               // todo remoteHSM
+               hsm = nil
+       } else {
+               hsm, err = pseudohsm.New(config.KeysDir())
+               if err != nil {
+                       cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
+               }
+       }
+
+       bcReactor := bc.NewBlockchainReactor(store, chain, txPool, accounts, assets, hsm, fastSync)
 
        bcReactor.SetLogger(logger.With("module", "blockchain"))
        sw.AddReactor("BLOCKCHAIN", bcReactor)