leader.go 25 KB

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