-
Notifications
You must be signed in to change notification settings - Fork 38
/
rpc_key_service.go
57 lines (49 loc) · 1.6 KB
/
rpc_key_service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package crypto
import (
"fmt"
gethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/ecies"
gethlog "github.com/ethereum/go-ethereum/log"
"github.com/ten-protocol/go-ten/go/common/log"
)
const rpcSuffix = 1
// RPCKeyService - manages the "TEN - RPC key" used by clients (like the TEN gateway) to make RPC requests
type RPCKeyService struct {
privKey *ecies.PrivateKey
sharedSecretService *SharedSecretService
logger gethlog.Logger
}
func NewRPCKeyService(sharedSecretService *SharedSecretService, logger gethlog.Logger) *RPCKeyService {
s := &RPCKeyService{
sharedSecretService: sharedSecretService,
logger: logger,
}
if sharedSecretService.IsInitialised() {
err := s.Initialise()
if err != nil {
logger.Crit("Failed to initialise RPC key service ", log.ErrKey, err)
return nil
}
}
return s
}
// Initialise - called when the shared secret is available
func (s *RPCKeyService) Initialise() error {
// the key is derived from the shared secret to allow transactions to be broadcast
bytes := s.sharedSecretService.ExtendEntropy([]byte{byte(rpcSuffix)})
ecdsaKey, err := gethcrypto.ToECDSA(bytes)
if err != nil {
return err
}
s.privKey = ecies.ImportECDSA(ecdsaKey)
return nil
}
func (s *RPCKeyService) DecryptRPCRequest(bytes []byte) ([]byte, error) {
return s.privKey.Decrypt(bytes, nil, nil)
}
func (s *RPCKeyService) PublicKey() ([]byte, error) {
if s.privKey == nil {
return nil, fmt.Errorf("rpc key service is not initialised")
}
return gethcrypto.CompressPubkey(s.privKey.PublicKey.ExportECDSA()), nil
}