leader.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. package main
  2. //#cgo CFLAGS: -fopenmp -O2
  3. //#cgo LDFLAGS: -lcrypto -lm -fopenmp
  4. //#include "../c/dpf.h"
  5. //#include "../c/okv.h"
  6. //#include "../c/dpf.c"
  7. //#include "../c/okv.c"
  8. import "C"
  9. //ssssssssssssss
  10. import (
  11. "crypto/rand"
  12. "crypto/rsa"
  13. "crypto/sha256"
  14. "crypto/tls"
  15. "crypto/x509"
  16. "crypto/x509/pkix"
  17. "encoding/pem"
  18. "fmt"
  19. "math/big"
  20. "net"
  21. "strconv"
  22. "sync"
  23. "time"
  24. lib "2PPS/lib"
  25. "unsafe"
  26. "golang.org/x/crypto/nacl/box"
  27. )
  28. //this stores all neccessary information for each client
  29. type clientKeys struct {
  30. roundsParticipating int
  31. PublicKey *[32]byte
  32. SharedSecret [32]byte
  33. PirQuery [][]byte
  34. }
  35. var clientData = make(map[net.Addr]clientKeys)
  36. var leaderPrivateKey *[32]byte
  37. var leaderPublicKey *[32]byte
  38. var followerPublicKey *[32]byte
  39. // every roundsBeforeUpdate the client updates his pirQuery, the sharedSecrets are updated locally
  40. const roundsBeforeUpdate int = 1
  41. const follower string = "127.0.0.1:4443"
  42. const maxNumberOfClients = 1000
  43. //needs to be changed at leader/follower/client at the same time
  44. const neededSubscriptions = 1
  45. var topicList []byte
  46. var topicAmount int
  47. var archiveTopicAmount int
  48. //works on my machine
  49. var numThreads = 12
  50. //has to be dividable by 32
  51. var dataLength int = 32
  52. //this needs to be adjusted peridodically
  53. var numRows int = 2
  54. //counts the number of rounds
  55. var round int = 1
  56. var startTime time.Time
  57. //adjust this for follower aswell
  58. var maxTimePerRound time.Duration = 5 * time.Second
  59. //channel for goroutine communication with clients
  60. var phase1Channel = make(chan net.Conn, maxNumberOfClients)
  61. var phase3Channel = make(chan net.Conn, maxNumberOfClients)
  62. func main() {
  63. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  64. if err != nil {
  65. panic(err)
  66. }
  67. //why is this neccessary?
  68. leaderPrivateKey = generatedPrivateKey
  69. leaderPublicKey = generatedPublicKey
  70. /*
  71. if len(os.Args) != 4 {
  72. fmt.Println("try again with: numThreads, dataLength, numRows")
  73. return
  74. }
  75. numThreads, _ = strconv.Atoi(os.Args[2])
  76. dataLength, _ = strconv.Atoi(os.Args[3])
  77. numRows, _ = strconv.Atoi(os.Args[4])
  78. */
  79. C.initializeServer(C.int(numThreads))
  80. //calls follower for setup
  81. conf := &tls.Config{
  82. InsecureSkipVerify: true,
  83. }
  84. followerConnection, err := tls.Dial("tcp", follower, conf)
  85. if err != nil {
  86. panic(err)
  87. }
  88. followerConnection.SetDeadline(time.Time{})
  89. //receives follower publicKey
  90. var tmpFollowerPubKey [32]byte
  91. _, err = followerConnection.Read(tmpFollowerPubKey[:])
  92. if err != nil {
  93. panic(err)
  94. }
  95. followerPublicKey = &tmpFollowerPubKey
  96. //send publicKey to follower
  97. _, err = followerConnection.Write(leaderPublicKey[:])
  98. if err != nil {
  99. panic(err)
  100. }
  101. //goroutine for accepting new clients
  102. go func() {
  103. leaderConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  104. if err != nil {
  105. panic(err)
  106. }
  107. // Generate a pem block with the private key
  108. keyPem := pem.EncodeToMemory(&pem.Block{
  109. Type: "RSA PRIVATE KEY",
  110. Bytes: x509.MarshalPKCS1PrivateKey(leaderConnectionPrivateKey),
  111. })
  112. tml := x509.Certificate{
  113. // you can add any attr that you need
  114. NotBefore: time.Now(),
  115. NotAfter: time.Now().AddDate(5, 0, 0),
  116. // you have to generate a different serial number each execution
  117. SerialNumber: big.NewInt(123123),
  118. Subject: pkix.Name{
  119. CommonName: "New Name",
  120. Organization: []string{"New Org."},
  121. },
  122. BasicConstraintsValid: true,
  123. }
  124. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &leaderConnectionPrivateKey.PublicKey, leaderConnectionPrivateKey)
  125. if err != nil {
  126. panic(err)
  127. }
  128. // Generate a pem block with the certificate
  129. certPem := pem.EncodeToMemory(&pem.Block{
  130. Type: "CERTIFICATE",
  131. Bytes: cert,
  132. })
  133. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  134. if err != nil {
  135. panic(err)
  136. }
  137. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  138. //listens for clients
  139. lnClients, err := tls.Listen("tcp", ":4441", config)
  140. if err != nil {
  141. panic(err)
  142. }
  143. defer lnClients.Close()
  144. for {
  145. clientConnection, err := lnClients.Accept()
  146. if err != nil {
  147. panic(err)
  148. }
  149. clientConnection.SetDeadline(time.Time{})
  150. //sends topicList so client can participate in phase 3 asap
  151. sendTopicLists(clientConnection)
  152. //send leader publicKey
  153. _, err = clientConnection.Write(leaderPublicKey[:])
  154. if err != nil {
  155. panic(err)
  156. }
  157. //send follower publicKey
  158. _, err = clientConnection.Write(followerPublicKey[:])
  159. if err != nil {
  160. panic(err)
  161. }
  162. var clientPublicKey *[32]byte
  163. var tmpClientPublicKey [32]byte
  164. //gets publicKey from client
  165. _, err = clientConnection.Read(tmpClientPublicKey[:])
  166. if err != nil {
  167. panic(err)
  168. }
  169. clientPublicKey = &tmpClientPublicKey
  170. //this is the key for map(client data)
  171. remoteAddress := clientConnection.RemoteAddr()
  172. //pirQuery will be added in phase 3
  173. //bs! only want to set roundsParticipating and answerAmount to 0, mb there is a better way
  174. //will work for now
  175. var emptyArray [32]byte
  176. var emptyByteArray [][]byte
  177. keys := clientKeys{0, clientPublicKey, emptyArray, emptyByteArray}
  178. clientData[remoteAddress] = keys
  179. phase1Channel <- clientConnection
  180. }
  181. }()
  182. wg := &sync.WaitGroup{}
  183. //the current phase
  184. phase := make([]byte, 1)
  185. //locks access to DB
  186. var m sync.Mutex
  187. for {
  188. //phase1
  189. startTime = time.Now()
  190. phase[0] = 1
  191. fmt.Println("phase1")
  192. //creates a new write Db for this round
  193. for i := 0; i < numRows; i++ {
  194. C.createDb(C.int(1), C.int(dataLength))
  195. }
  196. for id := 0; id < numThreads; id++ {
  197. wg.Add(1)
  198. followerConnection, err := tls.Dial("tcp", follower, conf)
  199. if err != nil {
  200. panic(err)
  201. }
  202. followerConnection.SetDeadline(time.Time{})
  203. go phase1(id, phase, followerConnection, wg, m, startTime)
  204. }
  205. wg.Wait()
  206. fmt.Println("phase2")
  207. //phase2
  208. followerConnection, err := tls.Dial("tcp", follower, conf)
  209. if err != nil {
  210. panic(err)
  211. }
  212. followerConnection.SetDeadline(time.Time{})
  213. phase2(followerConnection)
  214. //phase3
  215. fmt.Println("phase3")
  216. if round == 1 {
  217. //addTestTweets()
  218. }
  219. //no tweets -> continue to phase 1 and mb get tweets
  220. topicList, topicAmount = lib.GetTopicList(0)
  221. if len(topicList) == 0 {
  222. continue
  223. }
  224. phase[0] = 3
  225. startTime = time.Now()
  226. for id := 0; id < numThreads; id++ {
  227. wg.Add(1)
  228. followerConnection, err := tls.Dial("tcp", follower, conf)
  229. if err != nil {
  230. panic(err)
  231. }
  232. followerConnection.SetDeadline(time.Time{})
  233. go phase3(id, phase, followerConnection, wg, startTime)
  234. }
  235. wg.Wait()
  236. lib.CleanUpdbR(round)
  237. round++
  238. }
  239. }
  240. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m sync.Mutex, startTime time.Time) {
  241. roundAsBytes := intToByte(round)
  242. gotClient := make([]byte, 1)
  243. gotClient[0] = 0
  244. //wait until time is up
  245. for len(phase1Channel) == 0 {
  246. if time.Since(startTime) > maxTimePerRound {
  247. //tells follower that this worker is done
  248. _, err := followerConnection.Write(gotClient)
  249. if err != nil {
  250. panic(err)
  251. }
  252. wg.Done()
  253. return
  254. }
  255. time.Sleep(1 * time.Second)
  256. }
  257. for clientConnection := range phase1Channel {
  258. gotClient[0] = 1
  259. //tells follower that this worker got a clientConnection
  260. _, err := followerConnection.Write(gotClient)
  261. if err != nil {
  262. panic(err)
  263. }
  264. //sends clients publicKey to follower
  265. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  266. _, err = followerConnection.Write(clientPublicKey[:])
  267. if err != nil {
  268. panic(err)
  269. }
  270. //setup the worker-specific db
  271. dbSize := int(C.dbSize)
  272. db := make([][]byte, dbSize)
  273. for i := 0; i < dbSize; i++ {
  274. db[i] = make([]byte, int(C.db[i].dataSize))
  275. }
  276. //tells client that phase 1 has begun
  277. _, err = clientConnection.Write(phase)
  278. if err != nil {
  279. panic(err)
  280. }
  281. //tells client current round
  282. _, err = clientConnection.Write(roundAsBytes)
  283. if err != nil {
  284. panic(err)
  285. }
  286. //accept dpfQuery from client
  287. dpfLengthBytes := make([]byte, 4)
  288. _, err = clientConnection.Read(dpfLengthBytes)
  289. if err != nil {
  290. panic(err)
  291. }
  292. dpfLength := byteToInt(dpfLengthBytes)
  293. dpfQueryAEncrypted := make([]byte, dpfLength)
  294. dpfQueryBEncrypted := make([]byte, dpfLength)
  295. _, err = clientConnection.Read(dpfQueryAEncrypted)
  296. if err != nil {
  297. panic(err)
  298. }
  299. _, err = clientConnection.Read(dpfQueryBEncrypted)
  300. if err != nil {
  301. panic(err)
  302. }
  303. _, err = followerConnection.Write(dpfLengthBytes)
  304. if err != nil {
  305. panic(err)
  306. }
  307. _, err = followerConnection.Write(dpfQueryBEncrypted)
  308. if err != nil {
  309. panic(err)
  310. }
  311. //auditing starts here
  312. //generate seed
  313. var seed [16]byte
  314. _, err = rand.Read(seed[:])
  315. if err != nil {
  316. panic(err)
  317. }
  318. //send seed to client
  319. _, err = clientConnection.Write(seed[:])
  320. if err != nil {
  321. panic(err)
  322. }
  323. //send seed to follower
  324. _, err = followerConnection.Write(seed[:])
  325. if err != nil {
  326. panic(err)
  327. }
  328. //receive proofs
  329. auditLengthBytes := make([]byte, 4)
  330. _, err = clientConnection.Read(auditLengthBytes)
  331. if err != nil {
  332. panic(err)
  333. }
  334. auditLength := byteToInt(auditLengthBytes)
  335. clientAuditA := make([]byte, auditLength)
  336. clientAuditB := make([]byte, auditLength)
  337. _, err = clientConnection.Read(clientAuditA)
  338. if err != nil {
  339. panic(err)
  340. }
  341. _, err = clientConnection.Read(clientAuditB)
  342. if err != nil {
  343. panic(err)
  344. }
  345. //send client audit to follower
  346. _, err = followerConnection.Write(auditLengthBytes)
  347. if err != nil {
  348. panic(err)
  349. }
  350. _, err = followerConnection.Write(clientAuditB)
  351. if err != nil {
  352. panic(err)
  353. }
  354. //decrypts the client audit
  355. var decryptNonce [24]byte
  356. copy(decryptNonce[:], clientAuditA[:24])
  357. clientAuditA, ok := box.Open(nil, clientAuditA[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  358. if !ok {
  359. panic("clientAudit decryption not ok")
  360. }
  361. //decrypt dpfQueryA for sorting into db
  362. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  363. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  364. if !ok {
  365. panic("dpfQueryA decryption not ok")
  366. }
  367. vector := make([]byte, dbSize*16)
  368. //var str string
  369. //run dpf, xor into local db
  370. for i := 0; i < dbSize; i++ {
  371. ds := int(C.db[i].dataSize)
  372. dataShare := make([]byte, ds)
  373. pos := C.getUint128_t(C.int(i))
  374. v := C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  375. fmt.Println("")
  376. fmt.Println("v", i, v)
  377. /*if i == 99 {
  378. for i := 0; i < 16; i++ {
  379. str = str + strconv.FormatInt(int64(v[i]), 2)
  380. }
  381. fmt.Println(strconv.ParseInt(str, 2, len(str)))
  382. }*/
  383. copy(vector[i*16:(i+1)*16], C.GoBytes(unsafe.Pointer(&v), 16))
  384. for j := 0; j < ds; j++ {
  385. db[i][j] = db[i][j] ^ dataShare[j]
  386. }
  387. }
  388. //prepare for audit
  389. mVal := make([]byte, 16)
  390. cVal := make([]byte, 16)
  391. C.serverSetupProof(C.ctx[id], (*C.uchar)(&seed[0]), C.dbSize, (*C.uchar)(&vector[0]), (*C.uchar)(&mVal[0]), (*C.uchar)(&cVal[0]))
  392. //compute audit query
  393. auditResultA := make([]byte, 96)
  394. C.serverComputeQuery(C.ctx[id], (*C.uchar)(&seed[0]), (*C.uchar)(&mVal[0]), (*C.uchar)(&cVal[0]), (*C.uchar)(&clientAuditA[0]), (*C.uchar)(&auditResultA[0]))
  395. //encrypt leader audit result
  396. var nonce [24]byte
  397. //fill nonce with randomness
  398. _, err = rand.Read(nonce[:])
  399. if err != nil {
  400. panic("couldn't get randomness for nonce!")
  401. }
  402. auditResultAEncrypted := box.Seal(nonce[:], auditResultA, &nonce, followerPublicKey, leaderPrivateKey)
  403. encryptedAuditResultALengthBytes := intToByte(len(auditResultAEncrypted))
  404. //send audit result to follower
  405. _, err = followerConnection.Write(encryptedAuditResultALengthBytes)
  406. if err != nil {
  407. panic(err)
  408. }
  409. _, err = followerConnection.Write(auditResultAEncrypted)
  410. if err != nil {
  411. panic(err)
  412. }
  413. //receive follower audit result
  414. auditResultBEncryptedLengthBytes := make([]byte, 4)
  415. _, err = followerConnection.Read(auditResultBEncryptedLengthBytes)
  416. if err != nil {
  417. panic(err)
  418. }
  419. auditResultBEncryptedLength := byteToInt(auditResultBEncryptedLengthBytes)
  420. auditResultBEncrypted := make([]byte, auditResultBEncryptedLength)
  421. _, err = followerConnection.Read(auditResultBEncrypted)
  422. if err != nil {
  423. panic(err)
  424. }
  425. //decrypts the audit result from follower
  426. copy(decryptNonce[:], auditResultBEncrypted[:24])
  427. auditResultB, ok := box.Open(nil, auditResultBEncrypted[24:], &decryptNonce, followerPublicKey, leaderPrivateKey)
  428. if !ok {
  429. panic("auditResultB decryption not ok")
  430. }
  431. //compute audit result
  432. auditResult := int(C.serverVerifyProof((*C.uchar)(&auditResultA[0]), (*C.uchar)(&auditResultB[0])))
  433. if byteToInt(auditResultB) == 0 || auditResult == 0 {
  434. //fmt.Println("audit failed")
  435. } /*else {
  436. fmt.Println("audit passed")
  437. }
  438. */
  439. //xor the worker's DB into the main DB
  440. for i := 0; i < dbSize; i++ {
  441. m.Lock()
  442. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  443. m.Unlock()
  444. }
  445. phase3Channel <- clientConnection
  446. //loop that waits for new client or leaves phase1 if time is up
  447. for {
  448. if time.Since(startTime) < maxTimePerRound {
  449. //this worker handles the next client
  450. if len(phase1Channel) > 0 {
  451. break
  452. //this worker waits for next client
  453. } else {
  454. time.Sleep(1 * time.Second)
  455. }
  456. //times up
  457. } else {
  458. //tells follower that this worker is done
  459. gotClient[0] = 0
  460. _, err := followerConnection.Write(gotClient)
  461. if err != nil {
  462. panic(err)
  463. }
  464. wg.Done()
  465. return
  466. }
  467. }
  468. }
  469. }
  470. func phase2(followerConnection net.Conn) {
  471. //gets current seed
  472. seedLeader := make([]byte, 16)
  473. C.readSeed((*C.uchar)(&seedLeader[0]))
  474. //get data
  475. dbSize := int(C.dbSize)
  476. tmpdbLeader := make([][]byte, dbSize)
  477. for i := range tmpdbLeader {
  478. tmpdbLeader[i] = make([]byte, dataLength)
  479. }
  480. for i := 0; i < dbSize; i++ {
  481. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  482. }
  483. //writes seed to follower
  484. _, err := followerConnection.Write(seedLeader)
  485. if err != nil {
  486. panic(err)
  487. }
  488. //write data to follower
  489. //this is surely inefficent
  490. for i := 0; i < dbSize; i++ {
  491. _, err = followerConnection.Write(tmpdbLeader[i])
  492. if err != nil {
  493. panic(err)
  494. }
  495. }
  496. //receive seed from follower
  497. seedFollower := make([]byte, 16)
  498. _, err = followerConnection.Read(seedFollower)
  499. if err != nil {
  500. panic(err)
  501. }
  502. //receive data from follower
  503. tmpdbFollower := make([][]byte, dbSize)
  504. for i := range tmpdbFollower {
  505. tmpdbFollower[i] = make([]byte, dataLength)
  506. }
  507. for i := 0; i < dbSize; i++ {
  508. _, err = followerConnection.Read(tmpdbFollower[i])
  509. if err != nil {
  510. panic(err)
  511. }
  512. }
  513. //put together the db
  514. tmpdb := make([][]byte, dbSize)
  515. for i := range tmpdb {
  516. tmpdb[i] = make([]byte, dataLength)
  517. }
  518. //get own Ciphers
  519. ciphersLeader := make([]*C.uchar, dbSize)
  520. for i := 0; i < dbSize; i++ {
  521. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  522. }
  523. for i := 0; i < dbSize; i++ {
  524. C.getCipher(1, C.int(i), ciphersLeader[i])
  525. }
  526. //send own Ciphers to follower
  527. for i := 0; i < dbSize; i++ {
  528. _, err = followerConnection.Write(C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  529. if err != nil {
  530. panic(err)
  531. }
  532. }
  533. //receive ciphers from follower
  534. ciphersFollower := make([]byte, dbSize*16)
  535. for i := 0; i < dbSize; i++ {
  536. _, err = followerConnection.Read(ciphersFollower[i*16:])
  537. if err != nil {
  538. panic(err)
  539. }
  540. }
  541. //put in ciphers from follower
  542. for i := 0; i < dbSize; i++ {
  543. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  544. }
  545. //decrypt each row
  546. for i := 0; i < dbSize; i++ {
  547. C.decryptRow(C.int(i), (*C.uchar)(&tmpdb[i][0]), (*C.uchar)(&tmpdbLeader[i][0]), (*C.uchar)(&tmpdbFollower[i][0]), (*C.uchar)(&seedLeader[0]), (*C.uchar)(&seedFollower[0]))
  548. fmt.Println(i, tmpdb[i])
  549. fmt.Println("")
  550. }
  551. var tweets []lib.Tweet
  552. for i := 0; i < dbSize; i++ {
  553. //discard cover message
  554. if tmpdb[i][0] == 0 {
  555. continue
  556. } else {
  557. //reconstruct tweet
  558. var position int = 0
  559. var topics []string
  560. var topic string
  561. var text string
  562. for _, letter := range tmpdb[i] {
  563. if string(letter) == ";" {
  564. if topic != "" {
  565. topics = append(topics, topic)
  566. topic = ""
  567. }
  568. position++
  569. } else {
  570. if position == 0 {
  571. if string(letter) == "," {
  572. topics = append(topics, topic)
  573. topic = ""
  574. } else {
  575. topic = topic + string(letter)
  576. }
  577. } else if position == 1 {
  578. text = text + string(letter)
  579. }
  580. }
  581. }
  582. tweet := lib.Tweet{"", -1, topics, text, round}
  583. tweets = append(tweets, tweet)
  584. }
  585. }
  586. //fmt.Println("tweets recovered: ", tweets)
  587. //sort into read db
  588. lib.NewEntries(tweets, 0)
  589. C.resetDb()
  590. }
  591. func addTestTweets() {
  592. //creates test tweets
  593. tweets := make([]lib.Tweet, 5)
  594. for i := range tweets {
  595. j := i
  596. if i == 1 {
  597. j = 0
  598. }
  599. text := "Text " + strconv.Itoa(i)
  600. var topics []string
  601. topics = append(topics, "Topic "+strconv.Itoa(j))
  602. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  603. }
  604. lib.NewEntries(tweets, 0)
  605. }
  606. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  607. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, startTime time.Time) {
  608. gotClient := make([]byte, 1)
  609. gotClient[0] = 0
  610. //wait until time is up
  611. for len(phase3Channel) == 0 {
  612. if time.Since(startTime) > maxTimePerRound {
  613. //tells follower that this worker is done
  614. _, err := followerConnection.Write(gotClient)
  615. if err != nil {
  616. panic(err)
  617. }
  618. wg.Done()
  619. return
  620. }
  621. time.Sleep(1 * time.Second)
  622. }
  623. for clientConnection := range phase3Channel {
  624. gotClient[0] = 1
  625. //tells follower that this worker got a clientConnection
  626. _, err := followerConnection.Write(gotClient)
  627. if err != nil {
  628. panic(err)
  629. }
  630. _, err = clientConnection.Write(phase)
  631. if err != nil {
  632. panic(err)
  633. }
  634. /*
  635. possible Values
  636. 0 : new client
  637. leader expects sharedSecrets, expects pirQuery
  638. 1 : update needed
  639. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  640. 2 : no update needed
  641. nothing
  642. */
  643. subPhase := make([]byte, 1)
  644. //gets the data for the current client
  645. var clientKeys = clientData[clientConnection.RemoteAddr()]
  646. var roundsParticipating = clientKeys.roundsParticipating
  647. //client participates for the first time
  648. if roundsParticipating == 0 {
  649. subPhase[0] = 0
  650. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  651. subPhase[0] = 1
  652. } else {
  653. subPhase[0] = 2
  654. }
  655. //tells client what leader expects
  656. _, err = clientConnection.Write(subPhase)
  657. if err != nil {
  658. panic(err)
  659. }
  660. //tells follower what will happen
  661. _, err = followerConnection.Write(subPhase)
  662. if err != nil {
  663. panic(err)
  664. }
  665. //sends clients publicKey so follower knows which client is being served
  666. _, err = followerConnection.Write(clientKeys.PublicKey[:])
  667. if err != nil {
  668. panic(err)
  669. }
  670. //increases rounds participating for client
  671. clientKeys.roundsParticipating = roundsParticipating + 1
  672. //declaring variables here to prevent dupclicates later
  673. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  674. if subPhase[0] == 0 {
  675. sendTopicLists(clientConnection)
  676. clientKeys, _ = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]))
  677. } else if subPhase[0] == 1 {
  678. sendTopicLists(clientConnection)
  679. //updates sharedSecret
  680. sharedSecret = sha256.Sum256(sharedSecret[:])
  681. clientKeys.SharedSecret = sharedSecret
  682. clientKeys, _ = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]))
  683. }
  684. getSendTweets(clientKeys, nil, clientConnection, followerConnection)
  685. wantsArchive := make([]byte, 1)
  686. _, err = clientConnection.Read(wantsArchive)
  687. if err != nil {
  688. panic(err)
  689. }
  690. followerConnection.Write(wantsArchive)
  691. if err != nil {
  692. panic(err)
  693. }
  694. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  695. _, archiveQuerys := handlePirQuery(clientKeys, clientConnection, followerConnection, -1)
  696. getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection)
  697. }
  698. //saves all changes for client
  699. clientData[clientConnection.RemoteAddr()] = clientKeys
  700. phase1Channel <- clientConnection
  701. for {
  702. if time.Since(startTime) < maxTimePerRound {
  703. //this worker handles the next client
  704. if len(phase3Channel) > 0 {
  705. break
  706. //this worker waits for next client
  707. } else {
  708. time.Sleep(1 * time.Second)
  709. }
  710. //times up
  711. } else {
  712. //tells follower that this worker is done
  713. gotClient[0] = 0
  714. _, err := followerConnection.Write(gotClient)
  715. if err != nil {
  716. panic(err)
  717. }
  718. wg.Done()
  719. return
  720. }
  721. }
  722. }
  723. }
  724. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn) {
  725. tmpNeededSubscriptions := neededSubscriptions
  726. if archiveQuerys != nil {
  727. tmpNeededSubscriptions = len(archiveQuerys)
  728. }
  729. for i := 0; i < tmpNeededSubscriptions; i++ {
  730. //gets all requested tweets
  731. var tweets []byte
  732. if archiveQuerys == nil {
  733. tweets = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0)
  734. } else {
  735. tweets = lib.GetTweets(archiveQuerys[i], dataLength, 1)
  736. }
  737. //expand sharedSecret so it is of right length
  738. expandBy := len(tweets) / 32
  739. var expandedSharedSecret []byte
  740. for i := 0; i < expandBy; i++ {
  741. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  742. }
  743. fmt.Println(expandedSharedSecret)
  744. //Xor's sharedSecret with all tweets
  745. lib.Xor(expandedSharedSecret[:], tweets)
  746. //receives tweets from follower and Xor's them in
  747. tweetsLengthBytes := make([]byte, 4)
  748. _, err := followerConnection.Read(tweetsLengthBytes)
  749. if err != nil {
  750. panic(err)
  751. }
  752. tweetsReceivedLength := byteToInt(tweetsLengthBytes)
  753. receivedTweets := make([]byte, tweetsReceivedLength)
  754. _, err = followerConnection.Read(receivedTweets)
  755. if err != nil {
  756. panic(err)
  757. }
  758. lib.Xor(receivedTweets, tweets)
  759. //sends tweets to client
  760. tweetsLengthBytes = intToByte(len(tweets))
  761. _, err = clientConnection.Write(tweetsLengthBytes)
  762. if err != nil {
  763. panic(err)
  764. }
  765. _, err = clientConnection.Write(tweets)
  766. if err != nil {
  767. panic(err)
  768. }
  769. }
  770. }
  771. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int) (clientKeys, [][]byte) {
  772. clientPublicKey := clientKeys.PublicKey
  773. //gets the msg length
  774. msgLengthBytes := make([]byte, 4)
  775. _, err := clientConnection.Read(msgLengthBytes)
  776. if err != nil {
  777. panic(err)
  778. }
  779. msgLength := byteToInt(msgLengthBytes)
  780. leaderBox := make([]byte, msgLength)
  781. followerBox := make([]byte, msgLength)
  782. //gets the leader box
  783. _, err = clientConnection.Read(leaderBox)
  784. if err != nil {
  785. panic(err)
  786. }
  787. //gets the follower box
  788. _, err = clientConnection.Read(followerBox)
  789. if err != nil {
  790. panic(err)
  791. }
  792. tmpNeededSubscriptions := neededSubscriptions
  793. tmpTopicAmount := topicAmount
  794. if subPhase == -1 {
  795. archiveNeededSubscriptions := make([]byte, 4)
  796. _, err = clientConnection.Read(archiveNeededSubscriptions)
  797. if err != nil {
  798. panic(err)
  799. }
  800. _, err = followerConnection.Write(archiveNeededSubscriptions)
  801. if err != nil {
  802. panic(err)
  803. }
  804. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  805. tmpTopicAmount = archiveTopicAmount
  806. }
  807. //send length to follower
  808. _, err = followerConnection.Write(msgLengthBytes)
  809. if err != nil {
  810. panic(err)
  811. }
  812. //send box to follower
  813. _, err = followerConnection.Write(followerBox)
  814. if err != nil {
  815. panic(err)
  816. }
  817. var decryptNonce [24]byte
  818. copy(decryptNonce[:], leaderBox[:24])
  819. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  820. if !ok {
  821. panic("pirQuery decryption not ok")
  822. }
  823. //if sharedSecret is send
  824. if subPhase == 0 {
  825. //bs!
  826. var tmpSharedSecret [32]byte
  827. for index := 0; index < 32; index++ {
  828. tmpSharedSecret[index] = decrypted[index]
  829. }
  830. clientKeys.SharedSecret = tmpSharedSecret
  831. decrypted = decrypted[32:]
  832. }
  833. //transforms byteArray to ints of wanted topics
  834. pirQueryFlattened := decrypted
  835. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  836. for i := range pirQuerys {
  837. pirQuerys[i] = make([]byte, tmpTopicAmount)
  838. }
  839. for i := 0; i < tmpNeededSubscriptions; i++ {
  840. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  841. }
  842. //sets the pirQuery for the client in case whe are not archiving
  843. if subPhase != -1 {
  844. clientKeys.PirQuery = pirQuerys
  845. }
  846. return clientKeys, pirQuerys
  847. }
  848. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  849. var topics []string
  850. var topic string
  851. var position int = 0
  852. for _, letter := range topicsAsBytes {
  853. if string(letter) == "," {
  854. topics[position] = topic
  855. topic = ""
  856. position++
  857. } else {
  858. topic = topic + string(letter)
  859. }
  860. }
  861. return topics
  862. }
  863. func byteToInt(myBytes []byte) (x int) {
  864. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  865. return
  866. }
  867. func sendTopicLists(clientConnection net.Conn) {
  868. for i := 0; i < 2; i++ {
  869. var topicList []byte
  870. if i == 0 {
  871. topicList, topicAmount = lib.GetTopicList(i)
  872. } else {
  873. topicList, archiveTopicAmount = lib.GetTopicList(i)
  874. }
  875. topicListLengthBytes := intToByte(len(topicList))
  876. _, err := clientConnection.Write(topicListLengthBytes)
  877. if err != nil {
  878. panic(err)
  879. }
  880. _, err = clientConnection.Write(topicList)
  881. if err != nil {
  882. panic(err)
  883. }
  884. }
  885. }
  886. func intToByte(myInt int) (retBytes []byte) {
  887. retBytes = make([]byte, 4)
  888. retBytes[3] = byte((myInt >> 24) & 0xff)
  889. retBytes[2] = byte((myInt >> 16) & 0xff)
  890. retBytes[1] = byte((myInt >> 8) & 0xff)
  891. retBytes[0] = byte(myInt & 0xff)
  892. return
  893. }