Skip to content

Commit 0f3d362

Browse files
Remove context and fix e2e deployed (#40)
* Remove useless context from client * Add methods to generate KeyringPair from seed/phrase * Change end to end tests to use pivate key from ENV variable or skip tests if that variable is unset or empty
1 parent 55fdfad commit 0f3d362

5 files changed

Lines changed: 103 additions & 19 deletions

File tree

client/client.go

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,11 @@ type Client interface {
3434

3535
URL() string
3636
//MetaData(cache bool) (*MetadataVersioned, error)
37-
38-
Ctx() context.Context
3937
}
4038

4139
type client struct {
4240
gethrpc.Client
4341

44-
ctx context.Context
45-
4642
url string
4743

4844
// metadataVersioned is the metadata cache to prevent unnecessary requests
@@ -56,11 +52,6 @@ func (c client) URL() string {
5652
return c.url
5753
}
5854

59-
// Ctx returns the context.Context
60-
func (c client) Ctx() context.Context {
61-
return c.ctx
62-
}
63-
6455
// TODO move to State struct
6556
//func (c *client) MetaData(cache bool) (m *MetadataVersioned, err error) {
6657
// if cache && c.metadataVersioned != nil {
@@ -92,7 +83,7 @@ func Connect(url string) (Client, error) {
9283
if err != nil {
9384
return nil, err
9485
}
95-
cc := client{*c, ctx, url}
86+
cc := client{*c, url}
9687
return &cc, nil
9788
}
9889

signature/signature.go

Lines changed: 60 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@ package signature
1919
import (
2020
"encoding/hex"
2121
"fmt"
22-
"log"
22+
"os"
2323
"os/exec"
24+
"regexp"
2425
"strings"
2526
)
2627

27-
// const subkeyCmd = "/Users/philipstanislaus/go/src/github.com/paritytech/substrate/target/debug/subkey"
2828
const subkeyCmd = "subkey"
2929

3030
type KeyringPair struct {
@@ -36,6 +36,46 @@ type KeyringPair struct {
3636
PublicKey []byte
3737
}
3838

39+
var rePubKey = regexp.MustCompile(`Public key \(hex\): 0x([a-f0-9]*)\n`)
40+
var reAddress = regexp.MustCompile(`Address \(SS58\): ([a-zA-Z0-9]*)\n`)
41+
42+
func KeyringPairFromSecret(seedOrPhrase string) (KeyringPair, error) {
43+
// use "subkey" command for creation of public key and address
44+
cmd := exec.Command(subkeyCmd, "inspect", seedOrPhrase)
45+
46+
// execute the command, get the output
47+
out, err := cmd.Output()
48+
if err != nil {
49+
return KeyringPair{}, fmt.Errorf("failed to generate keyring pair from secret: %v", err.Error())
50+
}
51+
52+
if string(out) == "Invalid phrase/URI given" {
53+
return KeyringPair{}, fmt.Errorf("failed to generate keyring pair from secret: invalid phrase/URI given")
54+
}
55+
56+
// find the pub key
57+
resPk := rePubKey.FindStringSubmatch(string(out))
58+
if len(resPk) != 2 {
59+
return KeyringPair{}, fmt.Errorf("failed to generate keyring pair from secret, pubkey not found in output: %v", resPk)
60+
}
61+
pk, err := hex.DecodeString(string(resPk[1]))
62+
if err != nil {
63+
return KeyringPair{}, fmt.Errorf("failed to generate keyring pair from secret, could not hex decode pubkey: %v", string(resPk[1]))
64+
}
65+
66+
// find the address
67+
addr := reAddress.FindStringSubmatch(string(out))
68+
if len(addr) != 2 {
69+
return KeyringPair{}, fmt.Errorf("failed to generate keyring pair from secret, address not found in output: %v", addr)
70+
}
71+
72+
return KeyringPair{
73+
URI: seedOrPhrase,
74+
Address: addr[1],
75+
PublicKey: pk,
76+
}, nil
77+
}
78+
3979
var TestKeyringPairAlice = KeyringPair{
4080
URI: "//Alice",
4181
PublicKey: []byte{0xd4, 0x35, 0x93, 0xc7, 0x15, 0xfd, 0xd3, 0x1c, 0x61, 0x14, 0x1a, 0xbd, 0x4, 0xa9, 0x9f, 0xd6, 0x82, 0x2c, 0x85, 0x58, 0x85, 0x4c, 0xcd, 0xe3, 0x9a, 0x56, 0x84, 0xe7, 0xa5, 0x6d, 0xa2, 0x7d}, //nolint:lll
@@ -52,7 +92,7 @@ func Sign(data []byte, privateKeyURI string) ([]byte, error) {
5292
dataHex := hex.EncodeToString(data)
5393
cmd.Stdin = strings.NewReader(dataHex)
5494

55-
log.Printf("echo -n \"%v\" | %v sign %v --hex", dataHex, subkeyCmd, privateKeyURI)
95+
// log.Printf("echo -n \"%v\" | %v sign %v --hex", dataHex, subkeyCmd, privateKeyURI)
5696

5797
// execute the command, get the output
5898
out, err := cmd.Output()
@@ -85,12 +125,12 @@ func Verify(data []byte, sig []byte, privateKeyURI string) (bool, error) {
85125
dataHex := hex.EncodeToString(data)
86126
cmd.Stdin = strings.NewReader(dataHex)
87127

88-
log.Printf("echo -n \"%v\" | %v verify %v %v --hex", dataHex, subkeyCmd, sigHex, privateKeyURI)
128+
// log.Printf("echo -n \"%v\" | %v verify %v %v --hex", dataHex, subkeyCmd, sigHex, privateKeyURI)
89129

90130
// execute the command, get the output
91131
out, err := cmd.Output()
92132
if err != nil {
93-
log.Fatal("Failed to verify with subkey", err.Error())
133+
return false, fmt.Errorf("failed to verify with subkey: %v", err.Error())
94134
}
95135

96136
// remove line feed
@@ -102,3 +142,18 @@ func Verify(data []byte, sig []byte, privateKeyURI string) (bool, error) {
102142
valid := outStr == "Signature verifies correctly."
103143
return valid, nil
104144
}
145+
146+
// LoadKeyringPairFromEnv looks up whether the env variable TEST_PRIV_KEY is set and is not empty and tries to use its
147+
// content as a private phrase, seed or URI to derive a key ring pair. Panics if the private phrase, seed or URI is
148+
// not valid or the keyring pair cannot be derived
149+
func LoadKeyringPairFromEnv() (kp KeyringPair, ok bool) {
150+
priv, ok := os.LookupEnv("TEST_PRIV_KEY")
151+
if !ok || priv == "" {
152+
return kp, false
153+
}
154+
kp, err := KeyringPairFromSecret(priv)
155+
if err != nil {
156+
panic(fmt.Errorf("cannot load keyring pair from env or use fallback: %v", err))
157+
}
158+
return kp, true
159+
}

signature/signature_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,37 @@ import (
2121
"testing"
2222

2323
. "github.com/centrifuge/go-substrate-rpc-client/signature"
24+
"github.com/centrifuge/go-substrate-rpc-client/types"
2425
"github.com/stretchr/testify/assert"
2526
)
2627

28+
var testSecretPhrase = "little orbit comfort eyebrow talk pink flame ridge bring milk equip blood"
29+
var testSecretSeed = "0x167d9a020688544ea246b056799d6a771e97c9da057e4d0b87024537f99177bc"
30+
var testPubKey = "0xdc64bef918ddda3126a39a11113767741ddfdf91399f055e1d963f2ae1ec2535"
31+
var testAddressSS58 = "5H3gKVQU7DfNFfNGkgTrD7p715jjg7QXtat8X3UxiSyw7APW"
32+
33+
func TestKeyRingPairFromSecretPhrase(t *testing.T) {
34+
p, err := KeyringPairFromSecret(testSecretPhrase)
35+
assert.NoError(t, err)
36+
37+
assert.Equal(t, KeyringPair{
38+
URI: testSecretPhrase,
39+
Address: testAddressSS58,
40+
PublicKey: types.MustHexDecodeString(testPubKey),
41+
}, p)
42+
}
43+
44+
func TestKeyringPairFromSecretSeed(t *testing.T) {
45+
p, err := KeyringPairFromSecret(testSecretSeed)
46+
assert.NoError(t, err)
47+
48+
assert.Equal(t, KeyringPair{
49+
URI: testSecretSeed,
50+
Address: testAddressSS58,
51+
PublicKey: types.MustHexDecodeString(testPubKey),
52+
}, p)
53+
}
54+
2755
func TestSignAndVerify(t *testing.T) {
2856
data := []byte("hello!")
2957

teste2e/author_submit_and_watch_extrinsic_test.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ func TestAuthor_SubmitAndWatchExtrinsic(t *testing.T) {
3333
t.Skip("skipping end-to-end test in short mode.")
3434
}
3535

36+
from, ok := signature.LoadKeyringPairFromEnv()
37+
if !ok {
38+
t.Skip("skipping end-to-end that requires a private key because TEST_PRIV_KEY is not set or empty")
39+
}
40+
3641
api, err := gsrpc.NewSubstrateAPI(config.Default().RPCURL)
3742
if err != nil {
3843
panic(err)
@@ -70,7 +75,7 @@ func TestAuthor_SubmitAndWatchExtrinsic(t *testing.T) {
7075
panic(err)
7176
}
7277

73-
key, err := types.CreateStorageKey(meta, "System", "AccountNonce", signature.TestKeyringPairAlice.PublicKey)
78+
key, err := types.CreateStorageKey(meta, "System", "AccountNonce", from.PublicKey)
7479
if err != nil {
7580
panic(err)
7681
}
@@ -91,7 +96,7 @@ func TestAuthor_SubmitAndWatchExtrinsic(t *testing.T) {
9196
Tip: 0,
9297
}
9398

94-
err = ext.Sign(signature.TestKeyringPairAlice, o)
99+
err = ext.Sign(from, o)
95100
if err != nil {
96101
panic(err)
97102
}

teste2e/author_submit_extrinsic_test.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ func TestChain_SubmitExtrinsic(t *testing.T) {
3232
t.Skip("skipping end-to-end test in short mode.")
3333
}
3434

35+
from, ok := signature.LoadKeyringPairFromEnv()
36+
if !ok {
37+
t.Skip("skipping end-to-end that requires a private key because TEST_PRIV_KEY is not set or empty")
38+
}
39+
3540
api, err := gsrpc.NewSubstrateAPI(config.Default().RPCURL)
3641
if err != nil {
3742
panic(err)
@@ -74,7 +79,7 @@ func TestChain_SubmitExtrinsic(t *testing.T) {
7479
panic(err)
7580
}
7681

77-
key, err := types.CreateStorageKey(meta, "System", "AccountNonce", signature.TestKeyringPairAlice.PublicKey)
82+
key, err := types.CreateStorageKey(meta, "System", "AccountNonce", from.PublicKey)
7883
if err != nil {
7984
panic(err)
8085
}
@@ -98,7 +103,7 @@ func TestChain_SubmitExtrinsic(t *testing.T) {
98103

99104
extI := ext
100105

101-
err = extI.Sign(signature.TestKeyringPairAlice, o)
106+
err = extI.Sign(from, o)
102107
if err != nil {
103108
panic(err)
104109
}

0 commit comments

Comments
 (0)