main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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.New()
  177. shh.RegisterServer(&mailServer)
  178. mailServer.Init(shh, *argDBPath, msPassword, *argServerPoW)
  179. } else {
  180. shh = whisper.New()
  181. }
  182. asymKey = shh.NewIdentity()
  183. if nodeid == nil {
  184. nodeid = shh.NewIdentity()
  185. }
  186. maxPeers := 80
  187. if *bootstrapMode {
  188. maxPeers = 800
  189. }
  190. server = &p2p.Server{
  191. Config: p2p.Config{
  192. PrivateKey: nodeid,
  193. MaxPeers: maxPeers,
  194. Name: common.MakeName("whisper-go", "5.0"),
  195. Protocols: shh.Protocols(),
  196. ListenAddr: *argIP,
  197. NAT: nat.Any(),
  198. BootstrapNodes: peers,
  199. StaticNodes: peers,
  200. TrustedNodes: peers,
  201. },
  202. }
  203. }
  204. func startServer() {
  205. err := server.Start()
  206. if err != nil {
  207. utils.Fatalf("Failed to start Whisper peer: %s.", err)
  208. }
  209. fmt.Printf("my public key: %s \n", common.ToHex(crypto.FromECDSAPub(&asymKey.PublicKey)))
  210. fmt.Println(server.NodeInfo().Enode)
  211. if *bootstrapMode {
  212. configureNode()
  213. fmt.Println("Bootstrap Whisper node started")
  214. } else {
  215. fmt.Println("Whisper node started")
  216. // first see if we can establish connection, then ask for user input
  217. waitForConnection(true)
  218. configureNode()
  219. }
  220. if !*forwarderMode {
  221. fmt.Printf("Please type the message. To quit type: '%s'\n", quitCommand)
  222. }
  223. }
  224. func isKeyValid(k *ecdsa.PublicKey) bool {
  225. return k.X != nil && k.Y != nil
  226. }
  227. func configureNode() {
  228. var err error
  229. var p2pAccept bool
  230. if *forwarderMode {
  231. return
  232. }
  233. if *asymmetricMode {
  234. if len(*argPub) == 0 {
  235. s := scanLine("Please enter the peer's public key: ")
  236. pub = crypto.ToECDSAPub(common.FromHex(s))
  237. if !isKeyValid(pub) {
  238. utils.Fatalf("Error: invalid public key")
  239. }
  240. }
  241. }
  242. if *requestMail {
  243. p2pAccept = true
  244. if len(msPassword) == 0 {
  245. msPassword, err = console.Stdin.PromptPassword("Please enter the Mail Server password: ")
  246. if err != nil {
  247. utils.Fatalf("Failed to read Mail Server password: %s", err)
  248. }
  249. }
  250. }
  251. if !*asymmetricMode && !*forwarderMode && !*testMode {
  252. pass, err := console.Stdin.PromptPassword("Please enter the password: ")
  253. if err != nil {
  254. utils.Fatalf("Failed to read passphrase: %v", err)
  255. }
  256. if len(*argSalt) == 0 {
  257. argSalt = scanLineA("Please enter the salt: ")
  258. }
  259. symKey = pbkdf2.Key([]byte(pass), []byte(*argSalt), 65356, 32, sha256.New)
  260. if len(*argTopic) == 0 {
  261. generateTopic([]byte(pass), []byte(*argSalt))
  262. }
  263. }
  264. if *mailServerMode {
  265. if len(*argDBPath) == 0 {
  266. argDBPath = scanLineA("Please enter the path to DB file: ")
  267. }
  268. }
  269. filter := whisper.Filter{
  270. KeySym: symKey,
  271. KeyAsym: asymKey,
  272. Topics: []whisper.TopicType{topic},
  273. AcceptP2P: p2pAccept,
  274. }
  275. filterID = shh.Watch(&filter)
  276. fmt.Printf("Filter is configured for the topic: %x \n", topic)
  277. }
  278. func generateTopic(password, salt []byte) {
  279. const rounds = 4000
  280. const size = 128
  281. x1 := pbkdf2.Key(password, salt, rounds, size, sha512.New)
  282. x2 := pbkdf2.Key(password, salt, rounds, size, sha1.New)
  283. x3 := pbkdf2.Key(x1, x2, rounds, size, sha256.New)
  284. for i := 0; i < size; i++ {
  285. topic[i%whisper.TopicLength] ^= x3[i]
  286. }
  287. }
  288. func waitForConnection(timeout bool) {
  289. var cnt int
  290. var connected bool
  291. for !connected {
  292. time.Sleep(time.Millisecond * 50)
  293. connected = server.PeerCount() > 0
  294. if timeout {
  295. cnt++
  296. if cnt > 1000 {
  297. utils.Fatalf("Timeout expired, failed to connect")
  298. }
  299. }
  300. }
  301. fmt.Println("Connected to peer.")
  302. }
  303. func run() {
  304. defer mailServer.Close()
  305. startServer()
  306. defer server.Stop()
  307. shh.Start(nil)
  308. defer shh.Stop()
  309. if !*forwarderMode {
  310. go messageLoop()
  311. }
  312. if *requestMail {
  313. requestExpiredMessagesLoop()
  314. } else {
  315. sendLoop()
  316. }
  317. }
  318. func sendLoop() {
  319. for {
  320. s := scanLine("")
  321. if s == quitCommand {
  322. fmt.Println("Quit command received")
  323. close(done)
  324. break
  325. }
  326. sendMsg([]byte(s))
  327. if *asymmetricMode {
  328. // print your own message for convenience,
  329. // because in asymmetric mode it is impossible to decrypt it
  330. hour, min, sec := time.Now().Clock()
  331. from := crypto.PubkeyToAddress(asymKey.PublicKey)
  332. fmt.Printf("\n%02d:%02d:%02d <%x>: %s\n", hour, min, sec, from, s)
  333. }
  334. }
  335. }
  336. func scanLine(prompt string) string {
  337. if len(prompt) > 0 {
  338. fmt.Print(prompt)
  339. }
  340. txt, err := input.ReadString('\n')
  341. if err != nil {
  342. utils.Fatalf("input error: %s", err)
  343. }
  344. txt = strings.TrimRight(txt, "\n\r")
  345. return txt
  346. }
  347. func scanLineA(prompt string) *string {
  348. s := scanLine(prompt)
  349. return &s
  350. }
  351. func scanUint(prompt string) uint32 {
  352. s := scanLine(prompt)
  353. i, err := strconv.Atoi(s)
  354. if err != nil {
  355. utils.Fatalf("Fail to parse the lower time limit: %s", err)
  356. }
  357. return uint32(i)
  358. }
  359. func sendMsg(payload []byte) {
  360. params := whisper.MessageParams{
  361. Src: asymKey,
  362. Dst: pub,
  363. KeySym: symKey,
  364. Payload: payload,
  365. Topic: topic,
  366. TTL: uint32(*argTTL),
  367. PoW: *argPoW,
  368. WorkTime: uint32(*argWorkTime),
  369. }
  370. msg := whisper.NewSentMessage(&params)
  371. envelope, err := msg.Wrap(&params)
  372. if err != nil {
  373. fmt.Printf("failed to seal message: %v \n", err)
  374. return
  375. }
  376. err = shh.Send(envelope)
  377. if err != nil {
  378. fmt.Printf("failed to send message: %v \n", err)
  379. }
  380. }
  381. func messageLoop() {
  382. f := shh.GetFilter(filterID)
  383. if f == nil {
  384. utils.Fatalf("filter is not installed")
  385. }
  386. ticker := time.NewTicker(time.Millisecond * 50)
  387. for {
  388. select {
  389. case <-ticker.C:
  390. messages := f.Retrieve()
  391. for _, msg := range messages {
  392. printMessageInfo(msg)
  393. }
  394. case <-done:
  395. return
  396. }
  397. }
  398. }
  399. func printMessageInfo(msg *whisper.ReceivedMessage) {
  400. timestamp := fmt.Sprintf("%d", msg.Sent) // unix timestamp for diagnostics
  401. text := string(msg.Payload)
  402. var address common.Address
  403. if msg.Src != nil {
  404. address = crypto.PubkeyToAddress(*msg.Src)
  405. }
  406. if whisper.IsPubKeyEqual(msg.Src, &asymKey.PublicKey) {
  407. fmt.Printf("\n%s <%x>: %s\n", timestamp, address, text) // message from myself
  408. } else {
  409. fmt.Printf("\n%s [%x]: %s\n", timestamp, address, text) // message from a peer
  410. }
  411. }
  412. func requestExpiredMessagesLoop() {
  413. var key, peerID []byte
  414. var timeLow, timeUpp uint32
  415. var t string
  416. var xt, empty whisper.TopicType
  417. err := shh.AddSymKey(mailserver.MailServerKeyName, []byte(msPassword))
  418. if err != nil {
  419. utils.Fatalf("Failed to create symmetric key for mail request: %s", err)
  420. }
  421. key = shh.GetSymKey(mailserver.MailServerKeyName)
  422. peerID = extractIdFromEnode(*argEnode)
  423. shh.MarkPeerTrusted(peerID)
  424. for {
  425. timeLow = scanUint("Please enter the lower limit of the time range (unix timestamp): ")
  426. timeUpp = scanUint("Please enter the upper limit of the time range (unix timestamp): ")
  427. t = scanLine("Please enter the topic (hexadecimal): ")
  428. if len(t) >= whisper.TopicLength*2 {
  429. x, err := hex.DecodeString(t)
  430. if err != nil {
  431. utils.Fatalf("Failed to parse the topic: %s", err)
  432. }
  433. xt = whisper.BytesToTopic(x)
  434. }
  435. if timeUpp == 0 {
  436. timeUpp = 0xFFFFFFFF
  437. }
  438. data := make([]byte, 8+whisper.TopicLength)
  439. binary.BigEndian.PutUint32(data, timeLow)
  440. binary.BigEndian.PutUint32(data[4:], timeUpp)
  441. copy(data[8:], xt[:])
  442. if xt == empty {
  443. data = data[:8]
  444. }
  445. var params whisper.MessageParams
  446. params.PoW = *argServerPoW
  447. params.Payload = data
  448. params.KeySym = key
  449. params.Src = nodeid
  450. params.WorkTime = 5
  451. msg := whisper.NewSentMessage(&params)
  452. env, err := msg.Wrap(&params)
  453. if err != nil {
  454. utils.Fatalf("Wrap failed: %s", err)
  455. }
  456. err = shh.RequestHistoricMessages(peerID, env)
  457. if err != nil {
  458. utils.Fatalf("Failed to send P2P message: %s", err)
  459. }
  460. time.Sleep(time.Second * 5)
  461. }
  462. }
  463. func extractIdFromEnode(s string) []byte {
  464. n, err := discover.ParseNode(s)
  465. if err != nil {
  466. utils.Fatalf("Failed to parse enode: %s", err)
  467. return nil
  468. }
  469. return n.ID[:]
  470. }