main.go 13 KB

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