Skip to content

Commit

Permalink
server: Allow to derive a SipHashKey from a Blockhash
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexITC committed Mar 18, 2019
1 parent f6f3288 commit 2f3d2b0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
19 changes: 18 additions & 1 deletion server/app/com/xsn/explorer/gcs/SipHashKey.scala
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
package com.xsn.explorer.gcs

import com.google.common.primitives.Longs
import com.xsn.explorer.models.values.Blockhash

/**
* Represents a SipHash key using a 128-bit value, compatible with Guava.
*
* @param k0 the first half of the key
* @param k1 the second half of the key
*/
case class SipHashKey(k0: Long, k1: Long)
case class SipHashKey(k0: Long, k1: Long) {

override def toString: String = {
s"SipHashKey(${java.lang.Long.toUnsignedString(k0)}, ${java.lang.Long.toUnsignedString(k1)})"
}
}

object SipHashKey {

Expand All @@ -29,4 +35,15 @@ object SipHashKey {
val k1 = Longs.fromByteArray(key.drop(8).reverse.toArray)
SipHashKey(k0, k1)
}

def fromBtcutil(hash: Blockhash): SipHashKey = {
val bytes = hash
.string
.take(32)
.grouped(2)
.map { hex => Integer.parseInt(hex, 16).asInstanceOf[Byte] }
.toList

fromBtcutil(bytes)
}
}
8 changes: 8 additions & 0 deletions server/test/com/xsn/explorer/gcs/SipHashKeySpec.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.xsn.explorer.gcs

import com.xsn.explorer.models.values.Blockhash
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec

Expand All @@ -15,5 +16,12 @@ class SipHashKeySpec extends WordSpec {
key.k0 must be(4692295987881554252L)
key.k1 must be(1534194084347808571l)
}

"allow to use a blockhash" in {
val blockhash = Blockhash.from("00000b59875e80b0afc6c657bc5318d39e03532b7d97fb78a4c7bd55c4840c32").get
val expected = "SipHashKey(12718269283101769728, 15210999809835452079)"
val key = SipHashKey.fromBtcutil(blockhash)
key.toString must be(expected)
}
}
}

0 comments on commit 2f3d2b0

Please sign in to comment.