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.

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