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.

380 lines
9.4 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package keys_test
  2. import (
  3. "fmt"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/stretchr/testify/require"
  7. dbm "github.com/tendermint/tmlibs/db"
  8. "github.com/tendermint/go-crypto"
  9. "github.com/tendermint/go-crypto/keys"
  10. "github.com/tendermint/go-crypto/keys/words"
  11. )
  12. // TestKeyManagement makes sure we can manipulate these keys well
  13. func TestKeyManagement(t *testing.T) {
  14. // make the storage with reasonable defaults
  15. cstore := keys.New(
  16. dbm.NewMemDB(),
  17. words.MustLoadCodec("english"),
  18. )
  19. algo := keys.AlgoEd25519
  20. n1, n2, n3 := "personal", "business", "other"
  21. p1, p2 := "1234", "really-secure!@#$"
  22. // Check empty state
  23. l, err := cstore.List()
  24. require.Nil(t, err)
  25. assert.Empty(t, l)
  26. // create some keys
  27. _, err = cstore.Get(n1)
  28. assert.NotNil(t, err)
  29. i, _, err := cstore.Create(n1, p1, algo)
  30. require.Equal(t, n1, i.Name)
  31. require.Nil(t, err)
  32. _, _, err = cstore.Create(n2, p2, algo)
  33. require.Nil(t, err)
  34. // we can get these keys
  35. i2, err := cstore.Get(n2)
  36. assert.Nil(t, err)
  37. _, err = cstore.Get(n3)
  38. assert.NotNil(t, err)
  39. // list shows them in order
  40. keyS, err := cstore.List()
  41. require.Nil(t, err)
  42. require.Equal(t, 2, len(keyS))
  43. // note these are in alphabetical order
  44. assert.Equal(t, n2, keyS[0].Name)
  45. assert.Equal(t, n1, keyS[1].Name)
  46. assert.Equal(t, i2.PubKey, keyS[0].PubKey)
  47. // deleting a key removes it
  48. err = cstore.Delete("bad name", "foo")
  49. require.NotNil(t, err)
  50. err = cstore.Delete(n1, p1)
  51. require.Nil(t, err)
  52. keyS, err = cstore.List()
  53. require.Nil(t, err)
  54. assert.Equal(t, 1, len(keyS))
  55. _, err = cstore.Get(n1)
  56. assert.NotNil(t, err)
  57. // make sure that it only signs with the right password
  58. // tx := mock.NewSig([]byte("mytransactiondata"))
  59. // err = cstore.Sign(n2, p1, tx)
  60. // assert.NotNil(t, err)
  61. // err = cstore.Sign(n2, p2, tx)
  62. // assert.Nil(t, err, "%+v", err)
  63. // sigs, err := tx.Signers()
  64. // assert.Nil(t, err, "%+v", err)
  65. // if assert.Equal(t, 1, len(sigs)) {
  66. // assert.Equal(t, i2.PubKey, sigs[0])
  67. // }
  68. }
  69. // TestSignVerify does some detailed checks on how we sign and validate
  70. // signatures
  71. func TestSignVerify(t *testing.T) {
  72. // make the storage with reasonable defaults
  73. cstore := keys.New(
  74. dbm.NewMemDB(),
  75. words.MustLoadCodec("english"),
  76. )
  77. algo := keys.AlgoSecp256k1
  78. n1, n2 := "some dude", "a dudette"
  79. p1, p2 := "1234", "foobar"
  80. // create two users and get their info
  81. i1, _, err := cstore.Create(n1, p1, algo)
  82. require.Nil(t, err)
  83. i2, _, err := cstore.Create(n2, p2, algo)
  84. require.Nil(t, err)
  85. // let's try to sign some messages
  86. d1 := []byte("my first message")
  87. d2 := []byte("some other important info!")
  88. // try signing both data with both keys...
  89. s11, pub1, err := cstore.Sign(n1, p1, d1)
  90. require.Nil(t, err)
  91. require.Equal(t, i1.PubKey, pub1)
  92. s12, pub1, err := cstore.Sign(n1, p1, d2)
  93. require.Nil(t, err)
  94. require.Equal(t, i1.PubKey, pub1)
  95. s21, pub2, err := cstore.Sign(n2, p2, d1)
  96. require.Nil(t, err)
  97. require.Equal(t, i2.PubKey, pub2)
  98. s22, pub2, err := cstore.Sign(n2, p2, d2)
  99. require.Nil(t, err)
  100. require.Equal(t, i2.PubKey, pub2)
  101. // let's try to validate and make sure it only works when everything is proper
  102. cases := []struct {
  103. key crypto.PubKey
  104. data []byte
  105. sig crypto.Signature
  106. valid bool
  107. }{
  108. // proper matches
  109. {i1.PubKey, d1, s11, true},
  110. // change data, pubkey, or signature leads to fail
  111. {i1.PubKey, d2, s11, false},
  112. {i2.PubKey, d1, s11, false},
  113. {i1.PubKey, d1, s21, false},
  114. // make sure other successes
  115. {i1.PubKey, d2, s12, true},
  116. {i2.PubKey, d1, s21, true},
  117. {i2.PubKey, d2, s22, true},
  118. }
  119. for i, tc := range cases {
  120. valid := tc.key.VerifyBytes(tc.data, tc.sig)
  121. assert.Equal(t, tc.valid, valid, "%d", i)
  122. }
  123. }
  124. /*
  125. // TestSignWithLedger makes sure we have ledger compatibility with
  126. // the crypto store.
  127. //
  128. // This test will only succeed with a ledger attached to the computer
  129. // and the cosmos app open
  130. func TestSignWithLedger(t *testing.T) {
  131. if os.Getenv("WITH_LEDGER") == "" {
  132. t.Skip("Set WITH_LEDGER to run code on real ledger")
  133. }
  134. // make the storage with reasonable defaults
  135. cstore := keys.New(
  136. dbm.NewMemDB(),
  137. words.MustLoadCodec("english"),
  138. )
  139. n := "nano-s"
  140. p := "hard2hack"
  141. // create a nano user
  142. c, _, err := cstore.Create(n, p, nano.KeyLedgerEd25519)
  143. require.Nil(t, err, "%+v", err)
  144. assert.Equal(t, c.Key, n)
  145. _, ok := c.PubKey.Unwrap().(nano.PubKeyLedgerEd25519)
  146. require.True(t, ok)
  147. // make sure we can get it back
  148. info, err := cstore.Get(n)
  149. require.Nil(t, err, "%+v", err)
  150. assert.Equal(t, info.Key, n)
  151. key := info.PubKey
  152. require.False(t ,key.Empty())
  153. require.True(t, key.Equals(c.PubKey))
  154. // let's try to sign some messages
  155. d1 := []byte("welcome to cosmos")
  156. d2 := []byte("please turn on the app")
  157. // try signing both data with the ledger...
  158. s1, pub, err := cstore.Sign(n, p, d1)
  159. require.Nil(t, err)
  160. require.Equal(t, info.PubKey, pub)
  161. s2, pub, err := cstore.Sign(n, p, d2)
  162. require.Nil(t, err)
  163. require.Equal(t, info.PubKey, pub)
  164. // now, let's check those signatures work
  165. assert.True(t, key.VerifyBytes(d1, s1))
  166. assert.True(t, key.VerifyBytes(d2, s2))
  167. // and mismatched signatures don't
  168. assert.False(t, key.VerifyBytes(d1, s2))
  169. }
  170. */
  171. func assertPassword(t *testing.T, cstore keys.Keybase, name, pass, badpass string) {
  172. err := cstore.Update(name, badpass, pass)
  173. assert.NotNil(t, err)
  174. err = cstore.Update(name, pass, pass)
  175. assert.Nil(t, err, "%+v", err)
  176. }
  177. // TestExportImport tests exporting and importing keys.
  178. func TestExportImport(t *testing.T) {
  179. // make the storage with reasonable defaults
  180. db := dbm.NewMemDB()
  181. cstore := keys.New(
  182. db,
  183. words.MustLoadCodec("english"),
  184. )
  185. info, _, err := cstore.Create("john", "passphrase", keys.AlgoEd25519)
  186. assert.Nil(t, err)
  187. assert.Equal(t, info.Name, "john")
  188. addr := info.PubKey.Address()
  189. john, err := cstore.Get("john")
  190. assert.Nil(t, err)
  191. assert.Equal(t, john.Name, "john")
  192. assert.Equal(t, john.PubKey.Address(), addr)
  193. armor, err := cstore.Export("john")
  194. assert.Nil(t, err)
  195. err = cstore.Import("john2", armor)
  196. assert.Nil(t, err)
  197. john2, err := cstore.Get("john2")
  198. assert.Nil(t, err)
  199. assert.Equal(t, john.PubKey.Address(), addr)
  200. assert.Equal(t, john.Name, "john")
  201. assert.Equal(t, john, john2)
  202. }
  203. // TestAdvancedKeyManagement verifies update, import, export functionality
  204. func TestAdvancedKeyManagement(t *testing.T) {
  205. // make the storage with reasonable defaults
  206. cstore := keys.New(
  207. dbm.NewMemDB(),
  208. words.MustLoadCodec("english"),
  209. )
  210. algo := keys.AlgoSecp256k1
  211. n1, n2 := "old-name", "new name"
  212. p1, p2 := "1234", "foobar"
  213. // make sure key works with initial password
  214. _, _, err := cstore.Create(n1, p1, algo)
  215. require.Nil(t, err, "%+v", err)
  216. assertPassword(t, cstore, n1, p1, p2)
  217. // update password requires the existing password
  218. err = cstore.Update(n1, "jkkgkg", p2)
  219. assert.NotNil(t, err)
  220. assertPassword(t, cstore, n1, p1, p2)
  221. // then it changes the password when correct
  222. err = cstore.Update(n1, p1, p2)
  223. assert.Nil(t, err)
  224. // p2 is now the proper one!
  225. assertPassword(t, cstore, n1, p2, p1)
  226. // exporting requires the proper name and passphrase
  227. _, err = cstore.Export(n1 + ".notreal")
  228. assert.NotNil(t, err)
  229. _, err = cstore.Export(" " + n1)
  230. assert.NotNil(t, err)
  231. _, err = cstore.Export(n1 + " ")
  232. assert.NotNil(t, err)
  233. _, err = cstore.Export("")
  234. assert.NotNil(t, err)
  235. exported, err := cstore.Export(n1)
  236. require.Nil(t, err, "%+v", err)
  237. // import succeeds
  238. err = cstore.Import(n2, exported)
  239. assert.Nil(t, err)
  240. // second import fails
  241. err = cstore.Import(n2, exported)
  242. assert.NotNil(t, err)
  243. }
  244. // TestSeedPhrase verifies restoring from a seed phrase
  245. func TestSeedPhrase(t *testing.T) {
  246. // make the storage with reasonable defaults
  247. cstore := keys.New(
  248. dbm.NewMemDB(),
  249. words.MustLoadCodec("english"),
  250. )
  251. algo := keys.AlgoEd25519
  252. n1, n2 := "lost-key", "found-again"
  253. p1, p2 := "1234", "foobar"
  254. // make sure key works with initial password
  255. info, seed, err := cstore.Create(n1, p1, algo)
  256. require.Nil(t, err, "%+v", err)
  257. assert.Equal(t, n1, info.Name)
  258. assert.NotEmpty(t, seed)
  259. // now, let us delete this key
  260. err = cstore.Delete(n1, p1)
  261. require.Nil(t, err, "%+v", err)
  262. _, err = cstore.Get(n1)
  263. require.NotNil(t, err)
  264. // let us re-create it from the seed-phrase
  265. newInfo, err := cstore.Recover(n2, p2, seed)
  266. require.Nil(t, err, "%+v", err)
  267. assert.Equal(t, n2, newInfo.Name)
  268. assert.Equal(t, info.Address(), newInfo.Address())
  269. assert.Equal(t, info.PubKey, newInfo.PubKey)
  270. }
  271. func ExampleNew() {
  272. // Select the encryption and storage for your cryptostore
  273. cstore := keys.New(
  274. dbm.NewMemDB(),
  275. words.MustLoadCodec("english"),
  276. )
  277. ed := keys.AlgoEd25519
  278. sec := keys.AlgoSecp256k1
  279. // Add keys and see they return in alphabetical order
  280. bob, _, err := cstore.Create("Bob", "friend", ed)
  281. if err != nil {
  282. // this should never happen
  283. fmt.Println(err)
  284. } else {
  285. // return info here just like in List
  286. fmt.Println(bob.Name)
  287. }
  288. cstore.Create("Alice", "secret", sec)
  289. cstore.Create("Carl", "mitm", ed)
  290. info, _ := cstore.List()
  291. for _, i := range info {
  292. fmt.Println(i.Name)
  293. }
  294. // We need to use passphrase to generate a signature
  295. tx := []byte("deadbeef")
  296. sig, pub, err := cstore.Sign("Bob", "friend", tx)
  297. if err != nil {
  298. fmt.Println("don't accept real passphrase")
  299. }
  300. // and we can validate the signature with publically available info
  301. binfo, _ := cstore.Get("Bob")
  302. if !binfo.PubKey.Equals(bob.PubKey) {
  303. fmt.Println("Get and Create return different keys")
  304. }
  305. if pub.Equals(binfo.PubKey) {
  306. fmt.Println("signed by Bob")
  307. }
  308. if !pub.VerifyBytes(tx, sig) {
  309. fmt.Println("invalid signature")
  310. }
  311. // Output:
  312. // Bob
  313. // Alice
  314. // Bob
  315. // Carl
  316. // signed by Bob
  317. }