main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // This is a simple Whisper node. It could be used as a stand-alone bootstrap node.
  17. // Also, could be used for different test and diagnostics purposes.
  18. package main
  19. import (
  20. "bufio"
  21. "crypto/ecdsa"
  22. "crypto/sha1"
  23. "crypto/sha256"
  24. "crypto/sha512"
  25. "encoding/binary"
  26. "encoding/hex"
  27. "flag"
  28. "fmt"
  29. "os"
  30. "strconv"
  31. "strings"
  32. "time"
  33. "github.com/ethereum/go-ethereum/cmd/utils"
  34. "github.com/ethereum/go-ethereum/common"
  35. "github.com/ethereum/go-ethereum/console"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. "github.com/ethereum/go-ethereum/logger"
  38. "github.com/ethereum/go-ethereum/logger/glog"
  39. "github.com/ethereum/go-ethereum/p2p"
  40. "github.com/ethereum/go-ethereum/p2p/discover"
  41. "github.com/ethereum/go-ethereum/p2p/nat"
  42. "github.com/ethereum/go-ethereum/whisper/mailserver"
  43. whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
  44. "golang.org/x/crypto/pbkdf2"
  45. )
  46. const quitCommand = "~Q"
  47. // singletons
  48. var (
  49. server *p2p.Server
  50. shh *whisper.Whisper
  51. done chan struct{}
  52. mailServer mailserver.WMailServer
  53. input = bufio.NewReader(os.Stdin)
  54. )
  55. // encryption
  56. var (
  57. symKey []byte
  58. pub *ecdsa.PublicKey
  59. asymKey *ecdsa.PrivateKey
  60. nodeid *ecdsa.PrivateKey
  61. topic whisper.TopicType
  62. filterID uint32
  63. msPassword string
  64. )
  65. // cmd arguments
  66. var (
  67. echoMode = flag.Bool("e", false, "echo mode: prints some arguments for diagnostics")
  68. bootstrapMode = flag.Bool("b", false, "boostrap node: don't actively connect to peers, wait for incoming connections")
  69. forwarderMode = flag.Bool("f", false, "forwarder mode: only forward messages, neither send nor decrypt messages")
  70. mailServerMode = flag.Bool("s", false, "mail server mode: delivers expired messages on demand")
  71. requestMail = flag.Bool("r", false, "request expired messages from the bootstrap server")
  72. asymmetricMode = flag.Bool("a", false, "use asymmetric encryption")
  73. testMode = flag.Bool("t", false, "use of predefined parameters for diagnostics")
  74. generateKey = flag.Bool("k", false, "generate and show the private key")
  75. argTTL = flag.Uint("ttl", 30, "time-to-live for messages in seconds")
  76. argWorkTime = flag.Uint("work", 5, "work time in seconds")
  77. argPoW = flag.Float64("pow", whisper.MinimumPoW, "PoW for normal messages in float format (e.g. 2.7)")
  78. argServerPoW = flag.Float64("mspow", whisper.MinimumPoW, "PoW requirement for Mail Server request")
  79. argIP = flag.String("ip", "", "IP address and port of this node (e.g. 127.0.0.1:30303)")
  80. argSalt = flag.String("salt", "", "salt (for topic and key derivation)")
  81. argPub = flag.String("pub", "", "public key for asymmetric encryption")
  82. argDBPath = flag.String("dbpath", "", "path to the server's DB directory")
  83. argIDFile = flag.String("idfile", "", "file name with node id (private key)")
  84. argEnode = flag.String("boot", "", "bootstrap node you want to connect to (e.g. enode://e454......08d50@52.176.211.200:16428)")
  85. argTopic = flag.String("topic", "", "topic in hexadecimal format (e.g. 70a4beef)")
  86. )
  87. func main() {
  88. processArgs()
  89. initialize()
  90. run()
  91. }
  92. func processArgs() {
  93. flag.Parse()
  94. if len(*argIDFile) > 0 {
  95. var err error
  96. nodeid, err = crypto.LoadECDSA(*argIDFile)
  97. if err != nil {
  98. utils.Fatalf("Failed to load file [%s]: %s.", *argIDFile, err)
  99. }
  100. }
  101. const enodePrefix = "enode://"
  102. if len(*argEnode) > 0 {
  103. if (*argEnode)[:len(enodePrefix)] != enodePrefix {
  104. *argEnode = enodePrefix + *argEnode
  105. }
  106. }
  107. if len(*argTopic) > 0 {
  108. x, err := hex.DecodeString(*argTopic)
  109. if err != nil {
  110. utils.Fatalf("Failed to parse the topic: %s", err)
  111. }
  112. topic = whisper.BytesToTopic(x)
  113. }
  114. if *asymmetricMode && len(*argPub) > 0 {
  115. pub = crypto.ToECDSAPub(common.FromHex(*argPub))
  116. if !isKeyValid(pub) {
  117. utils.Fatalf("invalid public key")
  118. }
  119. }
  120. if *echoMode {
  121. echo()
  122. }
  123. }
  124. func echo() {
  125. fmt.Printf("ttl = %d \n", *argTTL)
  126. fmt.Printf("workTime = %d \n", *argWorkTime)
  127. fmt.Printf("pow = %f \n", *argPoW)
  128. fmt.Printf("mspow = %f \n", *argServerPoW)
  129. fmt.Printf("ip = %s \n", *argIP)
  130. fmt.Printf("salt = %s \n", *argSalt)
  131. fmt.Printf("pub = %s \n", common.ToHex(crypto.FromECDSAPub(pub)))
  132. fmt.Printf("idfile = %s \n", *argIDFile)
  133. fmt.Printf("dbpath = %s \n", *argDBPath)
  134. fmt.Printf("boot = %s \n", *argEnode)
  135. }
  136. func initialize() {
  137. glog.SetV(logger.Warn)
  138. glog.SetToStderr(true)
  139. done = make(chan struct{})
  140. var peers []*discover.Node
  141. var err error
  142. if *generateKey {
  143. key, err := crypto.GenerateKey()
  144. if err != nil {
  145. utils.Fatalf("Failed to generate private key: %s", err)
  146. }
  147. k := hex.EncodeToString(crypto.FromECDSA(key))
  148. fmt.Printf("Random private key: %s \n", k)
  149. os.Exit(0)
  150. }
  151. if *testMode {
  152. password := []byte("test password for symmetric encryption")
  153. salt := []byte("test salt for symmetric encryption")
  154. symKey = pbkdf2.Key(password, salt, 64, 32, sha256.New)
  155. topic = whisper.TopicType{0xFF, 0xFF, 0xFF, 0xFF}
  156. msPassword = "mail server test password"
  157. }
  158. if *bootstrapMode {
  159. if len(*argIP) == 0 {
  160. argIP = scanLineA("Please enter your IP and port (e.g. 127.0.0.1:30348): ")
  161. }
  162. } else {
  163. if len(*argEnode) == 0 {
  164. argEnode = scanLineA("Please enter the peer's enode: ")
  165. }
  166. peer := discover.MustParseNode(*argEnode)
  167. peers = append(peers, peer)
  168. }
  169. if *mailServerMode {
  170. if len(msPassword) == 0 {
  171. msPassword, err = console.Stdin.PromptPassword("Please enter the Mail Server password: ")
  172. if err != nil {
  173. utils.Fatalf("Failed to read Mail Server password: %s", err)
  174. }
  175. }
  176. shh = whisper.NewWhisper(&mailServer)
  177. mailServer.Init(shh, *argDBPath, msPassword, *argServerPoW)
  178. } else {
  179. shh = whisper.NewWhisper(nil)
  180. }
  181. asymKey = shh.NewIdentity()
  182. if nodeid == nil {
  183. nodeid = shh.NewIdentity()
  184. }
  185. server = &p2p.Server{
  186. Config: p2p.Config{
  187. PrivateKey: nodeid,
  188. MaxPeers: 128,
  189. Name: common.MakeName("whisper-go", "5.0"),
  190. Protocols: shh.Protocols(),
  191. ListenAddr: *argIP,
  192. NAT: nat.Any(),
  193. BootstrapNodes: peers,
  194. StaticNodes: peers,
  195. TrustedNodes: peers,
  196. },
  197. }
  198. }
  199. func startServer() {
  200. err := server.Start()
  201. if err != nil {
  202. utils.Fatalf("Failed to start Whisper peer: %s.", err)
  203. }
  204. fmt.Printf("my public key: %s \n", common.ToHex(crypto.FromECDSAPub(&asymKey.PublicKey)))
  205. fmt.Println(server.NodeInfo().Enode)
  206. if *bootstrapMode {
  207. configureNode()
  208. fmt.Println("Bootstrap Whisper node started")
  209. } else {
  210. fmt.Println("Whisper node started")
  211. // first see if we can establish connection, then ask for user input
  212. waitForConnection(true)
  213. configureNode()
  214. }
  215. if !*forwarderMode {
  216. fmt.Printf("Please type the message. To quit type: '%s'\n", quitCommand)
  217. }
  218. }
  219. func isKeyValid(k *ecdsa.PublicKey) bool {
  220. return k.X != nil && k.Y != nil
  221. }
  222. func configureNode() {
  223. var err error
  224. var p2pAccept bool
  225. if *forwarderMode {
  226. return
  227. }
  228. if *asymmetricMode {
  229. if len(*argPub) == 0 {
  230. s := scanLine("Please enter the peer's public key: ")
  231. pub = crypto.ToECDSAPub(common.FromHex(s))
  232. if !isKeyValid(pub) {
  233. utils.Fatalf("Error: invalid public key")
  234. }
  235. }
  236. }
  237. if *requestMail {
  238. p2pAccept = true
  239. if len(msPassword) == 0 {
  240. msPassword, err = console.Stdin.PromptPassword("Please enter the Mail Server password: ")
  241. if err != nil {
  242. utils.Fatalf("Failed to read Mail Server password: %s", err)
  243. }
  244. }
  245. }
  246. if !*asymmetricMode && !*forwarderMode && !*testMode {
  247. pass, err := console.Stdin.PromptPassword("Please enter the password: ")
  248. if err != nil {
  249. utils.Fatalf("Failed to read passphrase: %v", err)
  250. }
  251. if len(*argSalt) == 0 {
  252. argSalt = scanLineA("Please enter the salt: ")
  253. }
  254. symKey = pbkdf2.Key([]byte(pass), []byte(*argSalt), 65356, 32, sha256.New)
  255. if len(*argTopic) == 0 {
  256. generateTopic([]byte(pass), []byte(*argSalt))
  257. }
  258. }
  259. if *mailServerMode {
  260. if len(*argDBPath) == 0 {
  261. argDBPath = scanLineA("Please enter the path to DB file: ")
  262. }
  263. }
  264. filter := whisper.Filter{
  265. KeySym: symKey,
  266. KeyAsym: asymKey,
  267. Topics: []whisper.TopicType{topic},
  268. AcceptP2P: p2pAccept,
  269. }
  270. filterID = shh.Watch(&filter)
  271. fmt.Printf("Filter is configured for the topic: %x \n", topic)
  272. }
  273. func generateTopic(password, salt []byte) {
  274. const rounds = 4000
  275. const size = 128
  276. x1 := pbkdf2.Key(password, salt, rounds, size, sha512.New)
  277. x2 := pbkdf2.Key(password, salt, rounds, size, sha1.New)
  278. x3 := pbkdf2.Key(x1, x2, rounds, size, sha256.New)
  279. for i := 0; i < size; i++ {
  280. topic[i%whisper.TopicLength] ^= x3[i]
  281. }
  282. }
  283. func waitForConnection(timeout bool) {
  284. var cnt int
  285. var connected bool
  286. for !connected {
  287. time.Sleep(time.Millisecond * 50)
  288. connected = server.PeerCount() > 0
  289. if timeout {
  290. cnt++
  291. if cnt > 1000 {
  292. utils.Fatalf("Timeout expired, failed to connect")
  293. }
  294. }
  295. }
  296. fmt.Println("Connected to peer.")
  297. }
  298. func run() {
  299. defer mailServer.Close()
  300. startServer()
  301. defer server.Stop()
  302. shh.Start(nil)
  303. defer shh.Stop()
  304. if !*forwarderMode {
  305. go messageLoop()
  306. }
  307. if *requestMail {
  308. requestExpiredMessagesLoop()
  309. } else {
  310. sendLoop()
  311. }
  312. }
  313. func sendLoop() {
  314. for {
  315. s := scanLine("")
  316. if s == quitCommand {
  317. fmt.Println("Quit command received")
  318. close(done)
  319. break
  320. }
  321. sendMsg([]byte(s))
  322. if *asymmetricMode {
  323. // print your own message for convenience,
  324. // because in asymmetric mode it is impossible to decrypt it
  325. hour, min, sec := time.Now().Clock()
  326. from := crypto.PubkeyToAddress(asymKey.PublicKey)
  327. fmt.Printf("\n%02d:%02d:%02d <%x>: %s\n", hour, min, sec, from, s)
  328. }
  329. }
  330. }
  331. func scanLine(prompt string) string {
  332. if len(prompt) > 0 {
  333. fmt.Print(prompt)
  334. }
  335. txt, err := input.ReadString('\n')
  336. if err != nil {
  337. utils.Fatalf("input error: %s", err)
  338. }
  339. txt = strings.TrimRight(txt, "\n\r")
  340. return txt
  341. }
  342. func scanLineA(prompt string) *string {
  343. s := scanLine(prompt)
  344. return &s
  345. }
  346. func scanUint(prompt string) uint32 {
  347. s := scanLine(prompt)
  348. i, err := strconv.Atoi(s)
  349. if err != nil {
  350. utils.Fatalf("Fail to parse the lower time limit: %s", err)
  351. }
  352. return uint32(i)
  353. }
  354. func sendMsg(payload []byte) {
  355. params := whisper.MessageParams{
  356. Src: asymKey,
  357. Dst: pub,
  358. KeySym: symKey,
  359. Payload: payload,
  360. Topic: topic,
  361. TTL: uint32(*argTTL),
  362. PoW: *argPoW,
  363. WorkTime: uint32(*argWorkTime),
  364. }
  365. msg := whisper.NewSentMessage(&params)
  366. envelope, err := msg.Wrap(&params)
  367. if err != nil {
  368. fmt.Printf("failed to seal message: %v \n", err)
  369. return
  370. }
  371. err = shh.Send(envelope)
  372. if err != nil {
  373. fmt.Printf("failed to send message: %v \n", err)
  374. }
  375. }
  376. func messageLoop() {
  377. f := shh.GetFilter(filterID)
  378. if f == nil {
  379. utils.Fatalf("filter is not installed")
  380. }
  381. ticker := time.NewTicker(time.Millisecond * 50)
  382. for {
  383. select {
  384. case <-ticker.C:
  385. messages := f.Retrieve()
  386. for _, msg := range messages {
  387. printMessageInfo(msg)
  388. }
  389. case <-done:
  390. return
  391. }
  392. }
  393. }
  394. func printMessageInfo(msg *whisper.ReceivedMessage) {
  395. timestamp := fmt.Sprintf("%d", msg.Sent) // unix timestamp for diagnostics
  396. text := string(msg.Payload)
  397. var address common.Address
  398. if msg.Src != nil {
  399. address = crypto.PubkeyToAddress(*msg.Src)
  400. }
  401. if whisper.IsPubKeyEqual(msg.Src, &asymKey.PublicKey) {
  402. fmt.Printf("\n%s <%x>: %s\n", timestamp, address, text) // message from myself
  403. } else {
  404. fmt.Printf("\n%s [%x]: %s\n", timestamp, address, text) // message from a peer
  405. }
  406. }
  407. func requestExpiredMessagesLoop() {
  408. var key, peerID []byte
  409. var timeLow, timeUpp uint32
  410. var t string
  411. var xt, empty whisper.TopicType
  412. err := shh.AddSymKey(mailserver.MailServerKeyName, []byte(msPassword))
  413. if err != nil {
  414. utils.Fatalf("Failed to create symmetric key for mail request: %s", err)
  415. }
  416. key = shh.GetSymKey(mailserver.MailServerKeyName)
  417. peerID = extractIdFromEnode(*argEnode)
  418. shh.MarkPeerTrusted(peerID)
  419. for {
  420. timeLow = scanUint("Please enter the lower limit of the time range (unix timestamp): ")
  421. timeUpp = scanUint("Please enter the upper limit of the time range (unix timestamp): ")
  422. t = scanLine("Please enter the topic (hexadecimal): ")
  423. if len(t) >= whisper.TopicLength*2 {
  424. x, err := hex.DecodeString(t)
  425. if err != nil {
  426. utils.Fatalf("Failed to parse the topic: %s", err)
  427. }
  428. xt = whisper.BytesToTopic(x)
  429. }
  430. if timeUpp == 0 {
  431. timeUpp = 0xFFFFFFFF
  432. }
  433. data := make([]byte, 8+whisper.TopicLength)
  434. binary.BigEndian.PutUint32(data, timeLow)
  435. binary.BigEndian.PutUint32(data[4:], timeUpp)
  436. copy(data[8:], xt[:])
  437. if xt == empty {
  438. data = data[:8]
  439. }
  440. var params whisper.MessageParams
  441. params.PoW = *argServerPoW
  442. params.Payload = data
  443. params.KeySym = key
  444. params.Src = nodeid
  445. params.WorkTime = 5
  446. msg := whisper.NewSentMessage(&params)
  447. env, err := msg.Wrap(&params)
  448. if err != nil {
  449. utils.Fatalf("Wrap failed: %s", err)
  450. }
  451. err = shh.RequestHistoricMessages(peerID, env)
  452. if err != nil {
  453. utils.Fatalf("Failed to send P2P message: %s", err)
  454. }
  455. time.Sleep(time.Second * 5)
  456. }
  457. }
  458. func extractIdFromEnode(s string) []byte {
  459. n, err := discover.ParseNode(s)
  460. if err != nil {
  461. utils.Fatalf("Failed to parse enode: %s", err)
  462. return nil
  463. }
  464. return n.ID[:]
  465. }