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.

323 lines
10 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. "encoding/base64"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. "github.com/tendermint/tendermint/crypto/ed25519"
  12. "github.com/tendermint/tendermint/types"
  13. tmtime "github.com/tendermint/tendermint/types/time"
  14. )
  15. func TestGenLoadValidator(t *testing.T) {
  16. assert := assert.New(t)
  17. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  18. require.Nil(t, err)
  19. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  20. require.Nil(t, err)
  21. privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
  22. height := int64(100)
  23. privVal.LastSignState.Height = height
  24. privVal.Save()
  25. addr := privVal.GetAddress()
  26. privVal = LoadFilePV(tempKeyFile.Name(), tempStateFile.Name())
  27. assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same")
  28. assert.Equal(height, privVal.LastSignState.Height, "expected privval.LastHeight to have been saved")
  29. }
  30. func TestResetValidator(t *testing.T) {
  31. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  32. require.Nil(t, err)
  33. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  34. require.Nil(t, err)
  35. privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
  36. emptyState := FilePVLastSignState{filePath: tempStateFile.Name()}
  37. // new priv val has empty state
  38. assert.Equal(t, privVal.LastSignState, emptyState)
  39. // test vote
  40. height, round := int64(10), 1
  41. voteType := byte(types.PrevoteType)
  42. blockID := types.BlockID{Hash: []byte{1, 2, 3}, PartsHeader: types.PartSetHeader{}}
  43. vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID)
  44. err = privVal.SignVote("mychainid", vote)
  45. assert.NoError(t, err, "expected no error signing vote")
  46. // priv val after signing is not same as empty
  47. assert.NotEqual(t, privVal.LastSignState, emptyState)
  48. // priv val after AcceptNewConnection is same as empty
  49. privVal.Reset()
  50. assert.Equal(t, privVal.LastSignState, emptyState)
  51. }
  52. func TestLoadOrGenValidator(t *testing.T) {
  53. assert := assert.New(t)
  54. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  55. require.Nil(t, err)
  56. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  57. require.Nil(t, err)
  58. tempKeyFilePath := tempKeyFile.Name()
  59. if err := os.Remove(tempKeyFilePath); err != nil {
  60. t.Error(err)
  61. }
  62. tempStateFilePath := tempStateFile.Name()
  63. if err := os.Remove(tempStateFilePath); err != nil {
  64. t.Error(err)
  65. }
  66. privVal := LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath)
  67. addr := privVal.GetAddress()
  68. privVal = LoadOrGenFilePV(tempKeyFilePath, tempStateFilePath)
  69. assert.Equal(addr, privVal.GetAddress(), "expected privval addr to be the same")
  70. }
  71. func TestUnmarshalValidatorState(t *testing.T) {
  72. assert, require := assert.New(t), require.New(t)
  73. // create some fixed values
  74. serialized := `{
  75. "height": "1",
  76. "round": "1",
  77. "step": 1
  78. }`
  79. val := FilePVLastSignState{}
  80. err := cdc.UnmarshalJSON([]byte(serialized), &val)
  81. require.Nil(err, "%+v", err)
  82. // make sure the values match
  83. assert.EqualValues(val.Height, 1)
  84. assert.EqualValues(val.Round, 1)
  85. assert.EqualValues(val.Step, 1)
  86. // export it and make sure it is the same
  87. out, err := cdc.MarshalJSON(val)
  88. require.Nil(err, "%+v", err)
  89. assert.JSONEq(serialized, string(out))
  90. }
  91. func TestUnmarshalValidatorKey(t *testing.T) {
  92. assert, require := assert.New(t), require.New(t)
  93. // create some fixed values
  94. privKey := ed25519.GenPrivKey()
  95. pubKey := privKey.PubKey()
  96. addr := pubKey.Address()
  97. pubArray := [32]byte(pubKey.(ed25519.PubKeyEd25519))
  98. pubBytes := pubArray[:]
  99. privArray := [64]byte(privKey)
  100. privBytes := privArray[:]
  101. pubB64 := base64.StdEncoding.EncodeToString(pubBytes)
  102. privB64 := base64.StdEncoding.EncodeToString(privBytes)
  103. serialized := fmt.Sprintf(`{
  104. "address": "%s",
  105. "pub_key": {
  106. "type": "tendermint/PubKeyEd25519",
  107. "value": "%s"
  108. },
  109. "priv_key": {
  110. "type": "tendermint/PrivKeyEd25519",
  111. "value": "%s"
  112. }
  113. }`, addr, pubB64, privB64)
  114. val := FilePVKey{}
  115. err := cdc.UnmarshalJSON([]byte(serialized), &val)
  116. require.Nil(err, "%+v", err)
  117. // make sure the values match
  118. assert.EqualValues(addr, val.Address)
  119. assert.EqualValues(pubKey, val.PubKey)
  120. assert.EqualValues(privKey, val.PrivKey)
  121. // export it and make sure it is the same
  122. out, err := cdc.MarshalJSON(val)
  123. require.Nil(err, "%+v", err)
  124. assert.JSONEq(serialized, string(out))
  125. }
  126. func TestSignVote(t *testing.T) {
  127. assert := assert.New(t)
  128. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  129. require.Nil(t, err)
  130. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  131. require.Nil(t, err)
  132. privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
  133. block1 := types.BlockID{Hash: []byte{1, 2, 3}, PartsHeader: types.PartSetHeader{}}
  134. block2 := types.BlockID{Hash: []byte{3, 2, 1}, PartsHeader: types.PartSetHeader{}}
  135. height, round := int64(10), 1
  136. voteType := byte(types.PrevoteType)
  137. // sign a vote for first time
  138. vote := newVote(privVal.Key.Address, 0, height, round, voteType, block1)
  139. err = privVal.SignVote("mychainid", vote)
  140. assert.NoError(err, "expected no error signing vote")
  141. // try to sign the same vote again; should be fine
  142. err = privVal.SignVote("mychainid", vote)
  143. assert.NoError(err, "expected no error on signing same vote")
  144. // now try some bad votes
  145. cases := []*types.Vote{
  146. newVote(privVal.Key.Address, 0, height, round-1, voteType, block1), // round regression
  147. newVote(privVal.Key.Address, 0, height-1, round, voteType, block1), // height regression
  148. newVote(privVal.Key.Address, 0, height-2, round+4, voteType, block1), // height regression and different round
  149. newVote(privVal.Key.Address, 0, height, round, voteType, block2), // different block
  150. }
  151. for _, c := range cases {
  152. err = privVal.SignVote("mychainid", c)
  153. assert.Error(err, "expected error on signing conflicting vote")
  154. }
  155. // try signing a vote with a different time stamp
  156. sig := vote.Signature
  157. vote.Timestamp = vote.Timestamp.Add(time.Duration(1000))
  158. err = privVal.SignVote("mychainid", vote)
  159. assert.NoError(err)
  160. assert.Equal(sig, vote.Signature)
  161. }
  162. func TestSignProposal(t *testing.T) {
  163. assert := assert.New(t)
  164. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  165. require.Nil(t, err)
  166. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  167. require.Nil(t, err)
  168. privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
  169. block1 := types.BlockID{Hash: []byte{1, 2, 3}, PartsHeader: types.PartSetHeader{Total: 5, Hash: []byte{1, 2, 3}}}
  170. block2 := types.BlockID{Hash: []byte{3, 2, 1}, PartsHeader: types.PartSetHeader{Total: 10, Hash: []byte{3, 2, 1}}}
  171. height, round := int64(10), 1
  172. // sign a proposal for first time
  173. proposal := newProposal(height, round, block1)
  174. err = privVal.SignProposal("mychainid", proposal)
  175. assert.NoError(err, "expected no error signing proposal")
  176. // try to sign the same proposal again; should be fine
  177. err = privVal.SignProposal("mychainid", proposal)
  178. assert.NoError(err, "expected no error on signing same proposal")
  179. // now try some bad Proposals
  180. cases := []*types.Proposal{
  181. newProposal(height, round-1, block1), // round regression
  182. newProposal(height-1, round, block1), // height regression
  183. newProposal(height-2, round+4, block1), // height regression and different round
  184. newProposal(height, round, block2), // different block
  185. }
  186. for _, c := range cases {
  187. err = privVal.SignProposal("mychainid", c)
  188. assert.Error(err, "expected error on signing conflicting proposal")
  189. }
  190. // try signing a proposal with a different time stamp
  191. sig := proposal.Signature
  192. proposal.Timestamp = proposal.Timestamp.Add(time.Duration(1000))
  193. err = privVal.SignProposal("mychainid", proposal)
  194. assert.NoError(err)
  195. assert.Equal(sig, proposal.Signature)
  196. }
  197. func TestDifferByTimestamp(t *testing.T) {
  198. tempKeyFile, err := ioutil.TempFile("", "priv_validator_key_")
  199. require.Nil(t, err)
  200. tempStateFile, err := ioutil.TempFile("", "priv_validator_state_")
  201. require.Nil(t, err)
  202. privVal := GenFilePV(tempKeyFile.Name(), tempStateFile.Name())
  203. block1 := types.BlockID{Hash: []byte{1, 2, 3}, PartsHeader: types.PartSetHeader{Total: 5, Hash: []byte{1, 2, 3}}}
  204. height, round := int64(10), 1
  205. chainID := "mychainid"
  206. // test proposal
  207. {
  208. proposal := newProposal(height, round, block1)
  209. err := privVal.SignProposal(chainID, proposal)
  210. assert.NoError(t, err, "expected no error signing proposal")
  211. signBytes := proposal.SignBytes(chainID)
  212. sig := proposal.Signature
  213. timeStamp := proposal.Timestamp
  214. // manipulate the timestamp. should get changed back
  215. proposal.Timestamp = proposal.Timestamp.Add(time.Millisecond)
  216. var emptySig []byte
  217. proposal.Signature = emptySig
  218. err = privVal.SignProposal("mychainid", proposal)
  219. assert.NoError(t, err, "expected no error on signing same proposal")
  220. assert.Equal(t, timeStamp, proposal.Timestamp)
  221. assert.Equal(t, signBytes, proposal.SignBytes(chainID))
  222. assert.Equal(t, sig, proposal.Signature)
  223. }
  224. // test vote
  225. {
  226. voteType := byte(types.PrevoteType)
  227. blockID := types.BlockID{Hash: []byte{1, 2, 3}, PartsHeader: types.PartSetHeader{}}
  228. vote := newVote(privVal.Key.Address, 0, height, round, voteType, blockID)
  229. err := privVal.SignVote("mychainid", vote)
  230. assert.NoError(t, err, "expected no error signing vote")
  231. signBytes := vote.SignBytes(chainID)
  232. sig := vote.Signature
  233. timeStamp := vote.Timestamp
  234. // manipulate the timestamp. should get changed back
  235. vote.Timestamp = vote.Timestamp.Add(time.Millisecond)
  236. var emptySig []byte
  237. vote.Signature = emptySig
  238. err = privVal.SignVote("mychainid", vote)
  239. assert.NoError(t, err, "expected no error on signing same vote")
  240. assert.Equal(t, timeStamp, vote.Timestamp)
  241. assert.Equal(t, signBytes, vote.SignBytes(chainID))
  242. assert.Equal(t, sig, vote.Signature)
  243. }
  244. }
  245. func newVote(addr types.Address, idx int, height int64, round int, typ byte, blockID types.BlockID) *types.Vote {
  246. return &types.Vote{
  247. ValidatorAddress: addr,
  248. ValidatorIndex: idx,
  249. Height: height,
  250. Round: round,
  251. Type: types.SignedMsgType(typ),
  252. Timestamp: tmtime.Now(),
  253. BlockID: blockID,
  254. }
  255. }
  256. func newProposal(height int64, round int, blockID types.BlockID) *types.Proposal {
  257. return &types.Proposal{
  258. Height: height,
  259. Round: round,
  260. BlockID: blockID,
  261. Timestamp: tmtime.Now(),
  262. }
  263. }