You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

352 lines
11 KiB

privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
  1. package privval
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. "github.com/tendermint/tendermint/crypto/ed25519"
  13. "github.com/tendermint/tendermint/crypto/tmhash"
  14. tmjson "github.com/tendermint/tendermint/libs/json"
  15. tmrand "github.com/tendermint/tendermint/libs/rand"
  16. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  17. "github.com/tendermint/tendermint/types"
  18. tmtime "github.com/tendermint/tendermint/types/time"
  19. )
  20. func TestGenLoadValidator(t *testing.T) {
  21. assert := assert.New(t)
  22. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  23. require.Nil(t, err)
  24. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  25. require.Nil(t, err)
  26. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  27. require.NoError(t, err)
  28. height := int64(100)
  29. privVal.LastSignState.Height = height
  30. privVal.Save()
  31. addr := privVal.GetAddress()
  32. privVal, err = LoadFilePV(tempKeyFile.Name(), tempStateFile.Name())
  33. assert.NoError(err)
  34. assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same")
  35. assert.Equal(height, privVal.LastSignState.Height, "expected privval.LastHeight to have been saved")
  36. }
  37. func TestResetValidator(t *testing.T) {
  38. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  39. require.Nil(t, err)
  40. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  41. require.Nil(t, err)
  42. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  43. require.NoError(t, err)
  44. emptyState := FilePVLastSignState{filePath: tempStateFile.Name()}
  45. // new priv val has empty state
  46. assert.Equal(t, privVal.LastSignState, emptyState)
  47. // test vote
  48. height, round := int64(10), int32(1)
  49. voteType := tmproto.PrevoteType
  50. randBytes := tmrand.Bytes(tmhash.Size)
  51. blockID := types.BlockID{Hash: randBytes, PartSetHeader: types.PartSetHeader{}}
  52. vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID)
  53. err = privVal.SignVote(context.Background(), "mychainid", vote.ToProto())
  54. assert.NoError(t, err, "expected no error signing vote")
  55. // priv val after signing is not same as empty
  56. assert.NotEqual(t, privVal.LastSignState, emptyState)
  57. // priv val after AcceptNewConnection is same as empty
  58. privVal.Reset()
  59. assert.Equal(t, privVal.LastSignState, emptyState)
  60. }
  61. func TestLoadOrGenValidator(t *testing.T) {
  62. assert := assert.New(t)
  63. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  64. require.Nil(t, err)
  65. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  66. require.Nil(t, err)
  67. tempKeyFilePath := tempKeyFile.Name()
  68. if err := os.Remove(tempKeyFilePath); err != nil {
  69. t.Error(err)
  70. }
  71. tempStateFilePath := tempStateFile.Name()
  72. if err := os.Remove(tempStateFilePath); err != nil {
  73. t.Error(err)
  74. }
  75. privVal, err := LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath)
  76. require.NoError(t, err)
  77. addr := privVal.GetAddress()
  78. privVal, err = LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath)
  79. require.NoError(t, err)
  80. assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same")
  81. }
  82. func TestUnmarshalValidatorState(t *testing.T) {
  83. assert, require := assert.New(t), require.New(t)
  84. // create some fixed values
  85. serialized := `{
  86. "height": "1",
  87. "round": 1,
  88. "step": 1
  89. }`
  90. val := FilePVLastSignState{}
  91. err := tmjson.Unmarshal([]byte(serialized), &val)
  92. require.Nil(err, "%+v", err)
  93. // make sure the values match
  94. assert.EqualValues(val.Height, 1)
  95. assert.EqualValues(val.Round, 1)
  96. assert.EqualValues(val.Step, 1)
  97. // export it and make sure it is the same
  98. out, err := tmjson.Marshal(val)
  99. require.Nil(err, "%+v", err)
  100. assert.JSONEq(serialized, string(out))
  101. }
  102. func TestUnmarshalValidatorKey(t *testing.T) {
  103. assert, require := assert.New(t), require.New(t)
  104. // create some fixed values
  105. privKey := ed25519.GenPrivKey()
  106. pubKey := privKey.PubKey()
  107. addr := pubKey.Address()
  108. pubBytes := pubKey.Bytes()
  109. privBytes := privKey.Bytes()
  110. pubB64 := base64.StdEncoding.EncodeToString(pubBytes)
  111. privB64 := base64.StdEncoding.EncodeToString(privBytes)
  112. serialized := fmt.Sprintf(`{
  113. "address": "%s",
  114. "pub_key": {
  115. "type": "tendermint/PubKeyEd25519",
  116. "value": "%s"
  117. },
  118. "priv_key": {
  119. "type": "tendermint/PrivKeyEd25519",
  120. "value": "%s"
  121. }
  122. }`, addr, pubB64, privB64)
  123. val := FilePVKey{}
  124. err := tmjson.Unmarshal([]byte(serialized), &val)
  125. require.Nil(err, "%+v", err)
  126. // make sure the values match
  127. assert.EqualValues(addr, val.Address)
  128. assert.EqualValues(pubKey, val.PubKey)
  129. assert.EqualValues(privKey, val.PrivKey)
  130. // export it and make sure it is the same
  131. out, err := tmjson.Marshal(val)
  132. require.Nil(err, "%+v", err)
  133. assert.JSONEq(serialized, string(out))
  134. }
  135. func TestSignVote(t *testing.T) {
  136. assert := assert.New(t)
  137. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  138. require.Nil(t, err)
  139. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  140. require.Nil(t, err)
  141. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  142. require.NoError(t, err)
  143. randbytes := tmrand.Bytes(tmhash.Size)
  144. randbytes2 := tmrand.Bytes(tmhash.Size)
  145. block1 := types.BlockID{Hash: randbytes,
  146. PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}}
  147. block2 := types.BlockID{Hash: randbytes2,
  148. PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}}
  149. height, round := int64(10), int32(1)
  150. voteType := tmproto.PrevoteType
  151. // sign a vote for first time
  152. vote := newVote(privVal.Key.Address, 0, height, round, voteType, block1)
  153. v := vote.ToProto()
  154. err = privVal.SignVote(context.Background(), "mychainid", v)
  155. assert.NoError(err, "expected no error signing vote")
  156. // try to sign the same vote again; should be fine
  157. err = privVal.SignVote(context.Background(), "mychainid", v)
  158. assert.NoError(err, "expected no error on signing same vote")
  159. // now try some bad votes
  160. cases := []*types.Vote{
  161. newVote(privVal.Key.Address, 0, height, round-1, voteType, block1), // round regression
  162. newVote(privVal.Key.Address, 0, height-1, round, voteType, block1), // height regression
  163. newVote(privVal.Key.Address, 0, height-2, round+4, voteType, block1), // height regression and different round
  164. newVote(privVal.Key.Address, 0, height, round, voteType, block2), // different block
  165. }
  166. for _, c := range cases {
  167. cpb := c.ToProto()
  168. err = privVal.SignVote(context.Background(), "mychainid", cpb)
  169. assert.Error(err, "expected error on signing conflicting vote")
  170. }
  171. // try signing a vote with a different time stamp
  172. sig := vote.Signature
  173. vote.Timestamp = vote.Timestamp.Add(time.Duration(1000))
  174. err = privVal.SignVote(context.Background(), "mychainid", v)
  175. assert.NoError(err)
  176. assert.Equal(sig, vote.Signature)
  177. }
  178. func TestSignProposal(t *testing.T) {
  179. assert := assert.New(t)
  180. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  181. require.Nil(t, err)
  182. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  183. require.Nil(t, err)
  184. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  185. require.NoError(t, err)
  186. randbytes := tmrand.Bytes(tmhash.Size)
  187. randbytes2 := tmrand.Bytes(tmhash.Size)
  188. block1 := types.BlockID{Hash: randbytes,
  189. PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}}
  190. block2 := types.BlockID{Hash: randbytes2,
  191. PartSetHeader: types.PartSetHeader{Total: 10, Hash: randbytes2}}
  192. height, round := int64(10), int32(1)
  193. // sign a proposal for first time
  194. proposal := newProposal(height, round, block1)
  195. pbp := proposal.ToProto()
  196. err = privVal.SignProposal(context.Background(), "mychainid", pbp)
  197. assert.NoError(err, "expected no error signing proposal")
  198. // try to sign the same proposal again; should be fine
  199. err = privVal.SignProposal(context.Background(), "mychainid", pbp)
  200. assert.NoError(err, "expected no error on signing same proposal")
  201. // now try some bad Proposals
  202. cases := []*types.Proposal{
  203. newProposal(height, round-1, block1), // round regression
  204. newProposal(height-1, round, block1), // height regression
  205. newProposal(height-2, round+4, block1), // height regression and different round
  206. newProposal(height, round, block2), // different block
  207. }
  208. for _, c := range cases {
  209. err = privVal.SignProposal(context.Background(), "mychainid", c.ToProto())
  210. assert.Error(err, "expected error on signing conflicting proposal")
  211. }
  212. // try signing a proposal with a different time stamp
  213. sig := proposal.Signature
  214. proposal.Timestamp = proposal.Timestamp.Add(time.Duration(1000))
  215. err = privVal.SignProposal(context.Background(), "mychainid", pbp)
  216. assert.NoError(err)
  217. assert.Equal(sig, proposal.Signature)
  218. }
  219. func TestDifferByTimestamp(t *testing.T) {
  220. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  221. require.Nil(t, err)
  222. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  223. require.Nil(t, err)
  224. privVal, err := GenFilePV(tempKeyFile.Name(), tempStateFile.Name(), "")
  225. require.NoError(t, err)
  226. randbytes := tmrand.Bytes(tmhash.Size)
  227. block1 := types.BlockID{Hash: randbytes, PartSetHeader: types.PartSetHeader{Total: 5, Hash: randbytes}}
  228. height, round := int64(10), int32(1)
  229. chainID := "mychainid"
  230. // test proposal
  231. {
  232. proposal := newProposal(height, round, block1)
  233. pb := proposal.ToProto()
  234. err := privVal.SignProposal(context.Background(), chainID, pb)
  235. assert.NoError(t, err, "expected no error signing proposal")
  236. signBytes := types.ProposalSignBytes(chainID, pb)
  237. sig := proposal.Signature
  238. timeStamp := proposal.Timestamp
  239. // manipulate the timestamp. should get changed back
  240. pb.Timestamp = pb.Timestamp.Add(time.Millisecond)
  241. var emptySig []byte
  242. proposal.Signature = emptySig
  243. err = privVal.SignProposal(context.Background(), "mychainid", pb)
  244. assert.NoError(t, err, "expected no error on signing same proposal")
  245. assert.Equal(t, timeStamp, pb.Timestamp)
  246. assert.Equal(t, signBytes, types.ProposalSignBytes(chainID, pb))
  247. assert.Equal(t, sig, proposal.Signature)
  248. }
  249. // test vote
  250. {
  251. voteType := tmproto.PrevoteType
  252. blockID := types.BlockID{Hash: randbytes, PartSetHeader: types.PartSetHeader{}}
  253. vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID)
  254. v := vote.ToProto()
  255. err := privVal.SignVote(context.Background(), "mychainid", v)
  256. assert.NoError(t, err, "expected no error signing vote")
  257. signBytes := types.VoteSignBytes(chainID, v)
  258. sig := v.Signature
  259. timeStamp := vote.Timestamp
  260. // manipulate the timestamp. should get changed back
  261. v.Timestamp = v.Timestamp.Add(time.Millisecond)
  262. var emptySig []byte
  263. v.Signature = emptySig
  264. err = privVal.SignVote(context.Background(), "mychainid", v)
  265. assert.NoError(t, err, "expected no error on signing same vote")
  266. assert.Equal(t, timeStamp, v.Timestamp)
  267. assert.Equal(t, signBytes, types.VoteSignBytes(chainID, v))
  268. assert.Equal(t, sig, v.Signature)
  269. }
  270. }
  271. func newVote(addr types.Address, idx int32, height int64, round int32,
  272. typ tmproto.SignedMsgType, blockID types.BlockID) *types.Vote {
  273. return &types.Vote{
  274. ValidatorAddress: addr,
  275. ValidatorIndex: idx,
  276. Height: height,
  277. Round: round,
  278. Type: typ,
  279. Timestamp: tmtime.Now(),
  280. BlockID: blockID,
  281. }
  282. }
  283. func newProposal(height int64, round int32, blockID types.BlockID) *types.Proposal {
  284. return &types.Proposal{
  285. Height: height,
  286. Round: round,
  287. BlockID: blockID,
  288. Timestamp: tmtime.Now(),
  289. }
  290. }