Skip to content
Snippets Groups Projects
Commit ffa80a22 authored by Marvin Berstecher's avatar Marvin Berstecher Committed by Steffen Schulze
Browse files

Sprint 3

parent 876b01df
No related branches found
No related tags found
No related merge requests found
Showing
with 1111 additions and 0 deletions
# Cassandra Database
CASSANDRA_USERNAME=<to-be-added>
CASSANDRA_PASSWORD=<to-be-added>
CASSANDRA_HOST=<to-be-added>
CASSANDRA_PORT=<to-be-added>
CASSANDRA_KEYSPACE=<to-be-added>
# Service
APP_PORT=9090
\ No newline at end of file
package controller
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
type SynchronizationController struct{}
type Message struct {
Username string `json:"username"`
Text string `json:"text"`
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
// Allow all connections
return true
},
}
var clients = make(map[*websocket.Conn]bool)
// can be tested with: wscat -c ws://localhost:9090/synchronization -x '{"username":"name", "text":"text"}'
func (sc SynchronizationController) Synchronization(context *gin.Context) {
fmt.Println("websocket called!")
conn, err := upgrader.Upgrade(context.Writer, context.Request, nil)
if err != nil {
context.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
clients[conn] = true
go handleWebSocketConnection(conn)
}
func handleWebSocketConnection(conn *websocket.Conn) {
for {
var message Message
err := conn.ReadJSON(&message)
if err != nil {
conn.Close()
delete(clients, conn)
break
}
fmt.Println(message)
}
}
@hostname=localhost
@port=9090
@path=/message/receive
### DIDs
@from=did:peer:2.Ez6LSmg6eZ5FdMcE8PPSMMBWXDvDPQ2weFhbTWjabmgeo3hQh.Vz6Mknr5Zt1YeLF6XpCchBSCrepSoaXpFV93TR5YyhnU3nu8A.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHA6Ly9sb2NhbGhvc3Q6OTA5MC9tZXNzYWdlL3JlY2VpdmUiLCJhIjpbImRpZGNvbW0vdjIiXSwiciI6W119fQ
@to=did:peer:2.Ez6LSmg6eZ5FdMcE8PPSMMBWXDvDPQ2weFhbTWjabmgeo3hQh.Vz6Mknr5Zt1YeLF6XpCchBSCrepSoaXpFV93TR5YyhnU3nu8A.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHA6Ly9sb2NhbGhvc3Q6OTA5MC9tZXNzYWdlL3JlY2VpdmUiLCJhIjpbImRpZGNvbW0vdjIiXSwiciI6W119fQ
### Message (Coordinate-Mediation): Mediation request
POST http://{{hostname}}:{{port}}{{path}}
Content-Type: application/json
{
"id": "123456789abcdefghi",
"type": "https://didcomm.org/coordinate-mediation/3.0/mediate-request",
"body": {
},
"from": "{{from}}",
"to": [
"{{to}}"
],
"created_time": 5,
"expires_time": 50,
"attachments": []
}
### Message (Coordinate-Mediation): recipient update
POST http://{{hostname}}:{{port}}{{path}}
Content-Type: application/json
{
"id": "123456789abcdefghi",
"type": "https://didcomm.org/coordinate-mediation/3.0/recipient-update",
"body": {
"updates":[
{
"recipient_did": "did:peer:alice_did_for_bob",
"action": "add"
}
]
},
"from": "{{from}}",
"to": [
"{{to}}"
],
"created_time": 5,
"expires_time": 50,
"attachments": []
}
### Message (Coordinate-Mediation): recipient query
POST http://{{hostname}}:{{port}}{{path}}
Content-Type: application/json
{
"id": "123456780",
"type": "https://didcomm.org/coordinate-mediation/3.0/recipient-query",
"body": {
"paginate": {
"limit": 30,
"offset": 0
}
},
"from": "{{from}}",
"to": [
"{{to}}"
]
}
#!/usr/bin/env bash
# until printf "" 2>>/dev/null >>/dev/tcp/cassandra/9042; do
# sleep 5;
# echo "Waiting for cassandra...";
# done
echo "Creating keyspace and tables..."
# exec -it cassandra_db cqlsh -u cassandra -p cassandra -e "describe keyspaces"
# cqlsh cassandra_db -u cassandra -p cassandra -e "CREATE KEYSPACE IF NOT EXISTS dcc WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};"
## cqlsh cassandra -e "CREATE TABLE IF NOT EXISTS test.test (sensor_id uuid, registered_at timestamp, temperature int, location text, PRIMARY KEY ((sensor_id), registered_at)) WITH CLUSTERING ORDER BY (registered_at DESC);"
## cqlsh cassandra -e "CREATE TABLE IF NOT EXISTS test.sensors_locations (bucket text, location text, sensor_id uuid, PRIMARY KEY((bucket), location));"
## cqlsh cassandra -e "insert into test.sensors_locations (bucket, location, sensor_id) values ('default', 'kitchen', 99051fe9-6a9c-46c2-b949-38ef78858dd0);";
## cqlsh cassandra -e "insert into test.sensors_locations (bucket, location, sensor_id) values ('default', 'bedroom', 99051fe9-6a9c-46c2-b949-38ef78858dd1);";
## while true; do
## echo "Writing sample data...";
## cqlsh cassandra -e "insert into test.test (sensor_id, registered_at, temperature, location) values (99051fe9-6a9c-46c2-b949-38ef78858dd0, toTimestamp(now()), $(shuf -i 18-32 -n 1), 'kitchen');";
## cqlsh cassandra -e "insert into test.test (sensor_id, registered_at, temperature, location) values (99051fe9-6a9c-46c2-b949-38ef78858dd1, toTimestamp(now()), $(shuf -i 12-40 -n 1), 'bedroom');";
## sleep 5;
## done
# cqlsh -e "SELECT cast(location as text), cast(sensor_id as text) from test.sensors_locations where bucket = 'default'"
\ No newline at end of file
include:
- project: 'eclipse/xfsc/dev-ops/ci-templates'
file: 'standard-docker-ci.yaml'
ref: main
\ No newline at end of file
include:
- local: '/standard-docker-ci.yaml'
stages:
- build
- test
- release
unit-tests:
stage: test
rules:
- !reference [.rules, rules]
- if: '$CI_COMMIT_TAG == null'
image:
name: ${IMAGE_TAG_LOCATION}
script:
- go test ./...
check-code:
stage: test
rules:
- !reference [.rules, rules]
- if: '$CI_COMMIT_TAG == null'
image:
name: ${IMAGE_TAG_LOCATION}
script:
- go install honnef.co/go/tools/cmd/staticcheck@latest
- staticcheck ./...
\ No newline at end of file
package helper
import (
"fmt"
"github.com/spf13/viper"
)
type EnvironmentVariable string
const (
CASSANDRA_USERNAME EnvironmentVariable = "CASSANDRA_USERNAME"
CASSANDRA_PASSWORD EnvironmentVariable = "CASSANDRA_PASSWORD"
CASSANDRA_HOST EnvironmentVariable = "CASSANDRA_HOST"
CASSANDRA_PORT EnvironmentVariable = "CASSANDRA_PORT"
CASSANDRA_KEYSPACE EnvironmentVariable = "CASSANDRA_KEYSPACE"
APP_PORT EnvironmentVariable = "APP_PORT"
)
type DatabaseConfig struct {
Username string `mapstructure:"CASSANDRA_USERNAME"`
Password string `mapstructure:"CASSANDRA_PASSWORD"`
Endpoint string `mapstructure:"CASSANDRA_ENDPOINT"`
Port int `mapstructure:"CASSANDRA_PORT"`
Keyspace string `mapstructure:"CASSANDRA_KEYSPACE"`
}
func (env EnvironmentVariable) GetEnvironmentVariable() string {
switch env {
case CASSANDRA_USERNAME:
return getEnvironmentVariable(string(CASSANDRA_USERNAME))
case CASSANDRA_PASSWORD:
return getEnvironmentVariable(string(CASSANDRA_PASSWORD))
case CASSANDRA_HOST:
return getEnvironmentVariable(string(CASSANDRA_HOST))
case CASSANDRA_PORT:
return getEnvironmentVariable(string(CASSANDRA_PORT))
case CASSANDRA_KEYSPACE:
return getEnvironmentVariable(string(CASSANDRA_KEYSPACE))
case APP_PORT:
return getEnvironmentVariable(string(APP_PORT))
default:
return "Invalid environment variable key"
}
}
func initViper() {
viper.AddConfigPath(".")
viper.SetConfigName("app")
viper.SetConfigType("env")
}
func GetDatabaseConfig() (config DatabaseConfig, err error) {
initViper()
viper.AutomaticEnv()
err = viper.ReadInConfig()
if err != nil {
return
}
err = viper.Unmarshal(&config)
return
}
func getEnvironmentVariable(key string) (value string) {
initViper()
err := viper.ReadInConfig()
if err != nil {
fmt.Println("Error while reading config file: ", err)
}
value = viper.GetString(key)
if value == "" {
fmt.Println("No value for the environment variable '", key, "' found.")
}
return
}
package mediator
import (
"gaiax/didcommconnector/didcomm"
)
/// PackPlaintext
type PackErrorPair struct {
Err *didcomm.ErrorKind
Msg string
}
type PackResultCallback struct {
msgCh chan<- string
errCh chan<- PackErrorPair
}
func (m *PackResultCallback) New(msgCh chan<- string, errCh chan<- PackErrorPair) {
m.msgCh = msgCh
m.errCh = errCh
}
func (m *PackResultCallback) Success(result string) {
m.msgCh <- result
close(m.msgCh)
close(m.errCh)
}
func (m *PackResultCallback) Error(err *didcomm.ErrorKind, msg string) {
m.errCh <- PackErrorPair{err, msg}
close(m.errCh)
close(m.msgCh)
}
// / PackEncrypted
type PackEncryptedErrorPair struct {
Err *didcomm.ErrorKind
Msg string
}
type PackEncryptedSuccessPair struct {
Result string
Metadata didcomm.PackEncryptedMetadata
}
type PackEncryptedResultCallback struct {
sucCh chan<- PackEncryptedSuccessPair
errCh chan<- PackEncryptedErrorPair
}
func (m *PackEncryptedResultCallback) New(sucCh chan<- PackEncryptedSuccessPair, errCh chan<- PackEncryptedErrorPair) {
m.sucCh = sucCh
m.errCh = errCh
}
func (m *PackEncryptedResultCallback) Success(result string, metadata didcomm.PackEncryptedMetadata) {
m.sucCh <- PackEncryptedSuccessPair{result, metadata}
close(m.sucCh)
close(m.errCh)
}
func (m *PackEncryptedResultCallback) Error(err *didcomm.ErrorKind, msg string) {
m.errCh <- PackEncryptedErrorPair{err, msg}
close(m.errCh)
close(m.sucCh)
}
/// Unpack
type UnpackErrorPair struct {
Err *didcomm.ErrorKind
Msg string
}
type UnpackResultCallback struct {
msgCh chan<- didcomm.Message
errCh chan<- UnpackErrorPair
}
func (m *UnpackResultCallback) New(msgCh chan<- didcomm.Message, errCh chan<- UnpackErrorPair) {
m.msgCh = msgCh
m.errCh = errCh
}
func (m *UnpackResultCallback) Success(result didcomm.Message, metadata didcomm.UnpackMetadata) {
m.msgCh <- result
close(m.msgCh)
close(m.errCh)
}
func (m *UnpackResultCallback) Error(err *didcomm.ErrorKind, msg string) {
m.errCh <- UnpackErrorPair{err, msg}
close(m.errCh)
close(m.msgCh)
}
package mediator
import "gaiax/didcommconnector/didcomm"
type DatabaseAdapter interface {
AddMediatee(did string, routingKeys []string, service didcomm.Service) error
GetMediatee(did string) (*didcomm.DidDoc, error)
GetRoutingKeys(did string) (routingKeys []string)
AddRoutingKey(did string, newRoutingKey string)
DeleteRoutingKey(did string, routingKey string)
}
package mediator
import (
"errors"
"gaiax/didcommconnector/didcomm"
)
// Table Structure
// Connections
// did @id string
// isMediated bool
// routingKeys []string
// service didcomm.Service
// keylist []string
// Deny List
// did @id string
type DemoDatabase struct {
deny bool
}
func NewDemoDatabase() *DemoDatabase {
return &DemoDatabase{
deny: false,
}
}
func (d *DemoDatabase) AddMediatee(did string, routingKeys []string, service didcomm.Service) error {
return nil
}
func (d *DemoDatabase) GetMediatee(did string) (*didcomm.DidDoc, error) {
if d.deny {
return nil, errors.New("no mediatee found")
} else {
return &didcomm.DidDoc{}, nil
}
}
func (d *DemoDatabase) GetRoutingKeys(did string) (routingKeys []string) {
routingKeys = make([]string, 0)
// TODO: implement DB access to get rountign keys
return
}
func (d *DemoDatabase) AddRoutingKey(did string, newRoutingKey string) {
// TODO: implement to store new routing key
}
func (d *DemoDatabase) DeleteRoutingKey(did string, routingKey string) {
// TODO: implement to delete routing key
}
package mediator
import (
"fmt"
"gaiax/didcommconnector/didcomm"
)
// GetSecret(secretid string, cb *OnGetSecretResult) ErrorCode
// FindSecrets(secretids []string, cb *OnFindSecretsResult) ErrorCode
type DemoSecretsResolver struct {
secrets map[string]didcomm.Secret
}
func NewDemoSecretsResolver() *DemoSecretsResolver {
secrets := make(map[string]didcomm.Secret)
return &DemoSecretsResolver{
secrets: secrets,
}
}
func (d *DemoSecretsResolver) GetSecret(secretId string, cb *didcomm.OnGetSecretResult) didcomm.ErrorCode {
if secret, ok := d.secrets[secretId]; ok {
cb.Success(&secret)
return didcomm.ErrorCodeSuccess
} else {
errorKind := didcomm.NewErrorKindSecretNotFound()
cb.Error(errorKind, "Secret not found")
return didcomm.ErrorCodeError
}
}
func (d *DemoSecretsResolver) FindSecrets(secretIds []string, cb *didcomm.OnFindSecretsResult) didcomm.ErrorCode {
var secrets []string
for _, id := range secretIds {
if secret, ok := d.secrets[id]; ok {
secrets = append(secrets, secret.Id)
}
}
cb.Success(secrets)
return didcomm.ErrorCodeSuccess
}
func (d *DemoSecretsResolver) StoreSecret(secret didcomm.Secret) {
d.secrets[secret.Id] = secret
}
// Demo Print Function
func (d *DemoSecretsResolver) PrintSecrets() {
// print json like secrets
for _, secret := range d.secrets {
fmt.Println("{")
fmt.Println(" Id:", secret.Id)
fmt.Println(" Type:", secret.Type)
fmt.Println(" SecretMaterial:")
fmt.Println(" PrivateKeyMultibase:", secret.SecretMaterial.(didcomm.SecretMaterialMultibase).PrivateKeyMultibase)
fmt.Println("}")
}
}
package mediator
import (
"encoding/json"
"fmt"
"gaiax/didcommconnector/didcomm"
"io"
"net/http"
)
// type DidResolver interface {
// Resolve(did string, cb *OnDidResolverResult) ErrorCode
// }
type DidDocumentJSON struct {
DidDocument `json:"didDocument"`
DidDocumentMetadataJSON `json:"didDocumentMetadata"`
DidResolutionMetadataJSON `json:"didResolutionMetadata"`
}
// DidDocument represents the nested structure inside the main JSON.
type DidDocument struct {
Context []string `json:"@context"`
ID string `json:"id"`
VerificationMethod []VerificationMethod `json:"verificationMethod"`
KeyAgreement []string `json:"keyAgreement"`
Authentication []string `json:"authentication"`
AssertionMethod []string `json:"assertionMethod"`
CapabilityInvocation []string `json:"capabilityInvocation"`
CapabilityDelegation []string `json:"capabilityDelegation"`
Service []Service `json:"service"`
}
// VerificationMethod represents a nested structure inside the DidDocument.
type VerificationMethod struct {
ID string `json:"id"`
Type string `json:"type"`
Controller string `json:"controller"`
PublicKeyMultibase string `json:"publicKeyMultibase"`
}
// Service represents the nested structure inside the DidDocument for the "service" field.
type Service struct {
// RoutingKeys []string `json:"routingKeys"`
// Accept []string `json:"accept"`
Type string `json:"type"`
ID string `json:"id"`
ServiceEndpoint ServiceEndpoint `json:"serviceEndpoint"`
}
type ServiceEndpoint struct {
Uri string `json:"uri"`
Accept []string `json:"accept"`
RoutingKeys []string `json:"routingKeys"`
}
// DidDocumentMetadata represents the nested structure inside the main JSON for "didDocumentMetadata".
type DidDocumentMetadataJSON struct{}
// DidResolutionMetadata represents the nested structure inside the main JSON for "didResolutionMetadata".
type DidResolutionMetadataJSON struct {
ContentType string `json:"contentType"`
}
type DidResolver interface {
Resolve(did string, cb *didcomm.OnDidResolverResult) didcomm.ErrorCode
ResolveDid(did string) (*didcomm.DidDoc, error)
}
type UniverseDidResolver struct{}
func (u *UniverseDidResolver) New() *UniverseDidResolver {
return &UniverseDidResolver{}
}
func (u *UniverseDidResolver) Resolve(did string, cb *didcomm.OnDidResolverResult) didcomm.ErrorCode {
didDoc, err := u.ResolveDid(did)
if err != nil {
errorKind := didcomm.NewErrorKindSecretNotFound()
cb.Error(errorKind, err.Error())
return didcomm.ErrorCodeError
} else {
cb.Success(didDoc)
return didcomm.ErrorCodeSuccess
}
}
func (u *UniverseDidResolver) ResolveDid(did string) (*didcomm.DidDoc, error) {
// TODO: add environment variable for URI
resp, err := http.Get("http://localhost:8081/1.0/identifiers/" + did)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var didDocJSON DidDocumentJSON
err = json.Unmarshal(body, &didDocJSON)
if err != nil {
fmt.Println("Unmarshaling has failed:", err)
return nil, err
}
didDoc := didDocJsonToDidDoc(didDocJSON)
return didDoc, nil
}
func didDocJsonToDidDoc(ddJson DidDocumentJSON) *didcomm.DidDoc {
// Convert VerificationMethods
var VerificationMethods []didcomm.VerificationMethod = make([]didcomm.VerificationMethod, len(ddJson.DidDocument.VerificationMethod))
for i, vm := range ddJson.DidDocument.VerificationMethod {
VerificationMethodType, err := getVerificationType(vm.Type)
// TODO
if err != nil {
fmt.Println("Error:", err)
}
VerificationMethods[i] = didcomm.VerificationMethod{
Id: vm.ID,
Type: VerificationMethodType,
Controller: vm.Controller,
VerificationMaterial: didcomm.VerificationMaterialMultibase{
PublicKeyMultibase: vm.PublicKeyMultibase,
},
}
}
// Convert Services
var Services []didcomm.Service = make([]didcomm.Service, len(ddJson.DidDocument.Service))
for i, s := range ddJson.DidDocument.Service {
if s.Type != "DIDCommMessaging" {
// TODO
continue
}
Services[i] = didcomm.Service{
Id: s.ID,
ServiceEndpoint: didcomm.ServiceKindDidCommMessaging{
Value: didcomm.DidCommMessagingService{
Uri: s.ServiceEndpoint.Uri,
Accept: &s.ServiceEndpoint.Accept,
RoutingKeys: s.ServiceEndpoint.RoutingKeys,
},
},
}
}
didDoc := didcomm.DidDoc{
Id: ddJson.DidDocument.ID,
Authentication: ddJson.DidDocument.Authentication,
KeyAgreement: ddJson.DidDocument.KeyAgreement,
VerificationMethod: VerificationMethods,
Service: Services,
}
return &didDoc
}
func getVerificationType(stype string) (didcomm.VerificationMethodType, error) {
// VerificationMethodTypeJsonWebKey2020 VerificationMethodType = 1
// VerificationMethodTypeX25519KeyAgreementKey2019 VerificationMethodType = 2
// VerificationMethodTypeEd25519VerificationKey2018 VerificationMethodType = 3
// VerificationMethodTypeEcdsaSecp256k1VerificationKey2019 VerificationMethodType = 4
// VerificationMethodTypeX25519KeyAgreementKey2020 VerificationMethodType = 5
// VerificationMethodTypeEd25519VerificationKey2020 VerificationMethodType = 6
// VerificationMethodTypeOther VerificationMethodType = 7
switch stype {
case "JsonWebKey2020":
return didcomm.VerificationMethodTypeJsonWebKey2020, nil
case "X25519KeyAgreementKey2019":
return didcomm.VerificationMethodTypeX25519KeyAgreementKey2019, nil
case "Ed25519VerificationKey2018":
return didcomm.VerificationMethodTypeEd25519VerificationKey2018, nil
case "EcdsaSecp256k1VerificationKey2019":
return didcomm.VerificationMethodTypeEcdsaSecp256k1VerificationKey2019, nil
case "X25519KeyAgreementKey2020":
return didcomm.VerificationMethodTypeX25519KeyAgreementKey2020, nil
case "Ed25519VerificationKey2020":
return didcomm.VerificationMethodTypeEd25519VerificationKey2020, nil
default:
return didcomm.VerificationMethodTypeOther, fmt.Errorf("unknown VerificationMethodType: %s", stype)
}
}
package mediator
import "gaiax/didcommconnector/didcomm"
type Mediator struct {
Messages *didcomm.DidComm
SecretsResolver SecretsResolver
DidResolver DidResolver
Did string
EncryptionSecret didcomm.Secret
VerificationSecret didcomm.Secret
Database DatabaseAdapter
}
func NewMediator() *Mediator {
// didResolver := InitDidcommResovler()
var m Mediator
m.Did = m.getDid()
m.EncryptionSecret = m.getEncryptionSecret()
m.VerificationSecret = m.getVerificationSecret()
m.Database = NewDemoDatabase()
didResolver := &UniverseDidResolver{}
m.DidResolver = didResolver
secretsResolver := NewDemoSecretsResolver()
secretsResolver.StoreSecret(m.EncryptionSecret)
secretsResolver.StoreSecret(m.VerificationSecret)
m.SecretsResolver = secretsResolver
dcomm := didcomm.NewDidComm(didResolver, secretsResolver)
m.Messages = dcomm
return &m
}
func (m *Mediator) getDid() string {
// Did does not have meaningful service endpoint
did := "did:peer:2.Ez6LSc19SfftNpBDVqcd8NQtef2vinvR3W8s1wVeoYzwy5yiw.Vz6Mkno2XmnAxWb7YbyDJw9hmqWcTuAwQKbtaiw9tjqRjDvMz.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHA6Ly9sb2NhbGhvc3Q6OTA5MC9tZXNzYWdlL3JlY2VpdmUiLCJhIjpbImRpZGNvbW0vdjIiXSwiciI6W119fQ"
return did
}
func (m *Mediator) getVerificationSecret() didcomm.Secret {
kid := "6Mkno2XmnAxWb7YbyDJw9hmqWcTuAwQKbtaiw9tjqRjDvMz"
privateKey := "zrv4kkW1Czmu5VCKaHtfuoxFqSLAb4gwk7sjLc89DuzwMe3wZ6VTF5FtoLNRZFAgwBD63waizHTx7ih1yzB2tzAc8bW"
did := m.Did
secret := didcomm.Secret{
Id: did + "#" + kid,
Type: didcomm.SecretTypeEd25519VerificationKey2020,
SecretMaterial: didcomm.SecretMaterialMultibase{
PrivateKeyMultibase: privateKey,
},
}
return secret
}
func (m *Mediator) getEncryptionSecret() didcomm.Secret {
kid := "6LSc19SfftNpBDVqcd8NQtef2vinvR3W8s1wVeoYzwy5yiw"
// privateKey := "z3weggogbWATqzsigwidsXZ1MPFtJwnPgN3LEo5cS6PmzEva"
privateKey := "z3wehJqXpqKUbrdA3cDz9buSQXxfXYFLuVHUVACmAkNutGme"
did := m.Did
secret := didcomm.Secret{
Id: did + "#" + kid,
Type: didcomm.SecretTypeX25519KeyAgreementKey2020,
SecretMaterial: didcomm.SecretMaterialMultibase{
PrivateKeyMultibase: privateKey,
},
}
return secret
}
package mediator
import (
"fmt"
"gaiax/didcommconnector/didcomm"
)
func (m *Mediator) PackEncryptedMessage(message didcomm.Message, to string, from string) (response string, err error) {
// set PackEncryptedOptions
pencryptOpt := didcomm.PackEncryptedOptions{
ProtectSender: false,
Forward: true,
EncAlgAuth: didcomm.AuthCryptAlgA256cbcHs512Ecdh1puA256kw,
EncAlgAnon: didcomm.AnonCryptAlgA256cbcHs512EcdhEsA256kw,
}
// prepare callback
sucCh := make(chan PackEncryptedSuccessPair, 1)
errCh := make(chan PackEncryptedErrorPair, 1)
packEncryptCB := &PackEncryptedResultCallback{}
packEncryptCB.New(sucCh, errCh)
dc := m.Messages
// needs to be set, otherwise it will fail when unpacking
message.Typ = "application/didcomm-plain+json"
// Signing works as well
dc.PackEncrypted(message, to, &from, &from, pencryptOpt, packEncryptCB)
select {
case err := <-errCh:
fmt.Println("Error packing encrypted message:", err.Msg)
return "", err.Err
case suc := <-sucCh:
return suc.Result, nil
}
}
func (m *Mediator) PackPlainMessage(message didcomm.Message) (response string, err error) {
strCh := make(chan string, 1)
errCh := make(chan PackErrorPair, 1)
cb := &PackResultCallback{}
cb.New(strCh, errCh)
dc := m.Messages
message.Typ = "application/didcomm-plain+json"
dc.PackPlaintext(message, cb)
select {
case e := <-errCh:
fmt.Println("Error packing message:", e.Msg)
return "", e.Err
case m := <-strCh:
return m, nil
}
}
package mediator
import "gaiax/didcommconnector/didcomm"
// Is needed to have the store functionallity
type SecretsResolver interface {
GetSecret(secretid string, cb *didcomm.OnGetSecretResult) didcomm.ErrorCode
FindSecrets(secretids []string, cb *didcomm.OnFindSecretsResult) didcomm.ErrorCode
StoreSecret(secret didcomm.Secret)
}
package mediator
import (
"fmt"
"gaiax/didcommconnector/didcomm"
)
func (m *Mediator) UnpackMessage(body string) (didcomm.Message, error) {
// var message didcomm.Message = didcomm.Message{}
options := didcomm.UnpackOptions{
ExpectDecryptByAllKeys: true,
UnwrapReWrappingForward: true,
}
msgCh := make(chan didcomm.Message, 1)
errCh := make(chan UnpackErrorPair, 1)
unpackCB := &UnpackResultCallback{}
unpackCB.New(msgCh, errCh)
bodyString := string(body)
dc := m.Messages
go dc.Unpack(bodyString, options, unpackCB)
select {
case e := <-errCh:
fmt.Println("Error unpacking message:", e.Msg)
return didcomm.Message{}, e.Err
case message := <-msgCh:
return message, nil
}
}
package protocol
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestUpdate_RemoveSuccess(t *testing.T) {
// Sample data
did := "sampleDID"
dbKeys := []string{"key1"}
newKeys := []Update{
{RecipientDID: "key1", Action: "remove"},
}
updatedKeys, keysToAdd, keysToDelete, err := update(did, dbKeys, newKeys)
// Check if the result matches the expected outcome
expectedUpdatedKeys := []Update{
{RecipientDID: "key1", Action: "remove", Result: "success"},
}
expectedKeysToAdd := []string{}
expectedKeysToDelete := []string{"key1"}
assert.Equal(t, expectedUpdatedKeys, updatedKeys)
assert.Equal(t, expectedKeysToAdd, keysToAdd)
assert.Equal(t, expectedKeysToDelete, keysToDelete)
assert.Equal(t, err, nil)
}
func TestUpdate_AddSuccess(t *testing.T) {
// Sample data
did := "sampleDID"
dbKeys := []string{"key1", "key2", "key3"}
newKeys := []Update{
{RecipientDID: "key5", Action: "add"},
}
updatedKeys, keysToAdd, keysToDelete, err := update(did, dbKeys, newKeys)
// Check if the result matches the expected outcome
expectedUpdatedKeys := []Update{
{RecipientDID: "key5", Action: "add", Result: "success"},
}
expectedKeysToAdd := []string{"key5"}
expectedKeysToDelete := []string{}
assert.Equal(t, expectedUpdatedKeys, updatedKeys)
assert.Equal(t, expectedKeysToAdd, keysToAdd)
assert.Equal(t, expectedKeysToDelete, keysToDelete)
assert.Equal(t, err, nil)
}
func TestUpdate_RemoveClientError(t *testing.T) {
// Sample data
did := "sampleDID"
dbKeys := []string{"key1"}
newKeys := []Update{
{RecipientDID: "key2", Action: "remove"},
}
updatedKeys, keysToAdd, keysToDelete, err := update(did, dbKeys, newKeys)
// Check if the result matches the expected outcome
expectedUpdatedKeys := []Update{
{RecipientDID: "key2", Action: "remove", Result: "client_error"},
}
expectedKeysToAdd := []string{}
expectedKeysToDelete := []string{}
assert.Equal(t, expectedUpdatedKeys, updatedKeys)
assert.Equal(t, expectedKeysToAdd, keysToAdd)
assert.Equal(t, expectedKeysToDelete, keysToDelete)
assert.Equal(t, err, nil)
}
func TestUpdate_AddClientError(t *testing.T) {
// Sample data
did := "sampleDID"
dbKeys := []string{"key1", "key2", "key3"}
newKeys := []Update{
{RecipientDID: "key1", Action: "add"},
}
updatedKeys, keysToAdd, keysToDelete, err := update(did, dbKeys, newKeys)
// Check if the result matches the expected outcome
expectedUpdatedKeys := []Update{
{RecipientDID: "key1", Action: "add", Result: "no_changes"},
}
expectedKeysToAdd := []string{}
expectedKeysToDelete := []string{}
assert.Equal(t, expectedUpdatedKeys, updatedKeys)
assert.Equal(t, expectedKeysToAdd, keysToAdd)
assert.Equal(t, expectedKeysToDelete, keysToDelete)
assert.Equal(t, err, nil)
}
func TestUpdate_UnknwonAction(t *testing.T) {
// Sample data
did := "sampleDID"
dbKeys := []string{"key1", "key2", "key3"}
newKeys := []Update{
{RecipientDID: "key1", Action: "unknwonAction"},
}
updatedKeys, keysToAdd, keysToDelete, err := update(did, dbKeys, newKeys)
// Check if the result matches the expected outcome
expectedUpdatedKeys := []Update{}
expectedKeysToAdd := []string{}
expectedKeysToDelete := []string{}
assert.Equal(t, expectedUpdatedKeys, updatedKeys)
assert.Equal(t, expectedKeysToAdd, keysToAdd)
assert.Equal(t, expectedKeysToDelete, keysToDelete)
assert.Equal(t, err, nil)
}
package service
import (
"fmt"
"gaiax/didcommconnector/helper"
"gaiax/didcommconnector/model"
"github.com/gocql/gocql"
)
type CassandraService struct {
session *gocql.Session
}
func (c *CassandraService) GetById(id string) (con model.Connection, err error) {
defer func() {
c.session.Close()
}()
c.session = initSession()
query := "SELECT * FROM dcc WHERE id = ? ;"
if err = c.session.Query(query, id).Scan(&con.Id, &con.Did); err != nil {
fmt.Println("Error while getting by id. ", err)
return
}
fmt.Println("Selected object: ", con)
return con, nil
}
func (c *CassandraService) GetAll() (cons []model.Connection, err error) {
defer func() {
c.session.Close()
}()
c.session = initSession()
var con model.Connection
query := "SELECT * FROM dcc;"
m := map[string]interface{}{}
iter := c.session.Query(query).Iter()
for iter.MapScan(m) {
con = model.Connection{
Id: m["id"].(gocql.UUID),
Did: m["did"].(string),
}
cons = append(cons, con)
m = map[string]interface{}{}
}
fmt.Println("result: ", cons)
return cons, nil
}
func (c *CassandraService) Insert(did string) (id gocql.UUID, err error) {
defer func() {
c.session.Close()
}()
c.session = initSession()
uuid, err := gocql.RandomUUID()
query := "INSERT INTO dcc(id, did) VALUES (?, ?);"
if err = c.session.Query(query, uuid, did).Exec(); err != nil {
fmt.Println("Error while inserting. ", err)
return
}
return uuid, nil
}
func (c *CassandraService) Update(con model.Connection) (err error) {
defer func() {
c.session.Close()
}()
fmt.Println(con)
c.session = initSession()
query := "UPDATE dcc SET name=? WHERE id=? ;"
if err = c.session.Query(query, con.Did, con.Did).Exec(); err != nil {
fmt.Println("Error while updating. ", err)
return
}
return nil
}
func (c *CassandraService) DeleteDid(did string) (err error) {
defer func() {
c.session.Close()
}()
c.session = initSession()
query := "DELETE FROM dcc WHERE did = ? ;"
if err = c.session.Query(query, did).Exec(); err != nil {
fmt.Println("Error while deleting. ", err)
return
}
return nil
}
func (c *CassandraService) Delete(id gocql.UUID) (err error) {
defer func() {
c.session.Close()
}()
c.session = initSession()
query := "DELETE FROM dcc WHERE id = ? ;"
if err = c.session.Query(query, id).Exec(); err != nil {
fmt.Println("Error while deleting. ", err)
return
}
return nil
}
func initSession() *gocql.Session {
fmt.Println("Database session: Start initializing")
config, err := helper.GetDatabaseConfig()
if err != nil {
fmt.Println("Unable to load database configuration: ", err)
}
// todo init keyspace script on start
// cluster := gocql.NewCluster("172.18.0.2")
// cluster := gocql.NewCluster("localhost")
cluster := gocql.NewCluster("localhost")
cluster.Port = config.Port
cluster.Keyspace = config.Keyspace
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: config.Username,
Password: config.Password,
}
session, err := cluster.CreateSession()
if err != nil {
fmt.Println("Error while creating a DB session: ", err.Error())
}
fmt.Println("Initialize database session: Initialized")
return session
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment