aboutsummaryrefslogtreecommitdiff
path: root/pkg/rest/gnsregistrar.go
blob: 519cff0294dbf22cb0cd4e60045de161f0a1a4cd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
// This file is part of gnsregistrar, a GNS registrar implementation.
// Copyright (C) 2022 Martin Schanzenbach
//
// gnsregistrar is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// gnsregistrar is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later

package gnsregistrar

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/skip2/go-qrcode"
	"golang.org/x/text/currency"
	"golang.org/x/text/language"
	"golang.org/x/text/message"
	"gopkg.in/ini.v1"
	"github.com/schanzen/taler-go/pkg/merchant"
	talerutil "github.com/schanzen/taler-go/pkg/util"
)


type RegistrationMetadata struct {	
	Expiration uint64 `json:"expiration"`
	Paid bool `json:"paid"`	
	OrderID string `json:"order_id"`
	NeedsPaymentUntil time.Time `json:"needs_payment_until"`
}

type IdentityInfo struct {
	Pubkey string `json:"pubkey"`
	Name string `json:"name"`	
}


type GnunetError struct {
	Description string `json:"error"`
	Code uint32 `json:"error_code"`	
}

type RecordData struct {
	Value string `json:"value"`
	RecordType string `json:"record_type"`
	RelativeExpiration uint64 `json:"relative_expiration"`
	IsPrivate bool `json:"is_private"`
	IsRelativeExpiration bool `json:"is_relative_expiration"`
	IsSupplemental bool `json:"is_supplemental"`
	IsShadow bool `json:"is_shadow"`
	IsMaintenance bool `json:"is_maintenance"`
	
}

type NamestoreRecord struct {
	RecordName string `json:"record_name"`
	Records []RecordData `json:"data"`
}

// Registrar is the primary object of the service
type Registrar struct {

	// The main router
	Router *mux.Router

	// Our configuration from the config.json
	Cfg *ini.File

	// Map of supported validators as defined in the configuration
	Validators map[string]bool

	// landing page
	LandingTpl *template.Template

	// name page
	NameTpl *template.Template

	// buy names page
	BuyTpl *template.Template

	// Merchant object
	Merchant merchant.Merchant

	// Relative record expiration (NOT registration expiration!)
	RelativeDelegationExpiration time.Duration

	// Registration expiration (NOT record expiration!)
	RelativeRegistrationExpiration time.Duration

	// Payment expiration (time you have to pay for registration)
	PaymentExpiration time.Duration

	// Name of our root zone
	RootZoneName string

	// Key of our root zone
	RootZoneKey string

	// Suggested suffix for our zone
	SuffixHint string

	// Gnunet REST API basename
	GnunetUrl string
	
	// Registrar base URL
	BaseUrl string

	// Cost for a registration
	RegistrationCost *talerutil.Amount

}

type VersionResponse struct {
	// libtool-style representation of the Merchant protocol version, see
	// https://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning
	// The format is "current:revision:age".
	Version string `json:"version"`
}

func (t *Registrar) configResponse(w http.ResponseWriter, r *http.Request) {
	cfg := VersionResponse{
		Version: "0:0:0",
	}
	w.Header().Set("Content-Type", "application/json")
	response, _ := json.Marshal(cfg)
	w.Write(response)
}

// FIXME: Implement https://docs.taler.net/design-documents/051-fractional-digits.html and move to taler-go
func (t *Registrar) localizedAmountString() (string) {
	p := message.NewPrinter(language.English)
	costStr := t.RegistrationCost.String()
	costSplit := strings.Split(costStr, ":")
	left := costSplit[0]
	right := costSplit[1]
	cur, err := currency.ParseISO(left)
	if nil != err {
		return fmt.Sprintf("%s %s", right, left)
	}
	amf, _ := strconv.ParseFloat(right, 8)
	v := currency.Symbol(cur.Amount(amf))
	return p.Sprint(v)
}

func (t *Registrar) landingPage(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	fullData := map[string]interface{}{
		"suffixHint":     t.SuffixHint,
		"zoneKey":        t.RootZoneKey,
		"error":     r.URL.Query().Get("error"),
	}
	t.LandingTpl.Execute(w, fullData)
	return
}

func (t *Registrar) registerName(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	var namestoreRequest NamestoreRecord
	var delegationRecord RecordData
	var metadataRecord RecordData
	var gnunetError GnunetError
	var registrationMetadata RegistrationMetadata
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	delegationRecord.IsPrivate = false
	delegationRecord.IsRelativeExpiration = true
	delegationRecord.IsSupplemental = false
	delegationRecord.IsMaintenance = false
	delegationRecord.IsShadow = false
	delegationRecord.RecordType = guessDelegationRecordType(r.URL.Query().Get("zkey"))
	delegationRecord.RelativeExpiration = uint64(t.RelativeDelegationExpiration.Microseconds())
	delegationRecord.Value = r.URL.Query().Get("zkey")
	metadataRecord.IsPrivate = true
	metadataRecord.IsRelativeExpiration = true
	metadataRecord.IsSupplemental = false
	metadataRecord.IsMaintenance = true
	metadataRecord.IsShadow = false
	metadataRecord.RecordType = "TXT" // FIXME use new recory type
	metadataRecord.RelativeExpiration = uint64(t.RelativeDelegationExpiration.Microseconds())
	registrationMetadata = RegistrationMetadata{
		Paid: false,
		Expiration: uint64(time.Now().Add(t.RelativeRegistrationExpiration).UnixMicro()),
	}
	metadataRecordValue, err := json.Marshal(registrationMetadata)
	if nil != err {	
		http.Redirect(w, r, "/name?label="+vars["label"] + "&error=Registration failed", http.StatusSeeOther)
		return
	}
	metadataRecord.Value = string(metadataRecordValue)
	namestoreRequest.RecordName = vars["label"]
	namestoreRequest.Records = []RecordData{delegationRecord,metadataRecord}
	reqString, _ := json.Marshal(namestoreRequest)
	// FIXME handle errors here
	fmt.Println(namestoreRequest)
	resp, err := http.Post(t.GnunetUrl+"/namestore/" + t.RootZoneName, "application/json", bytes.NewBuffer(reqString))
	resp.Body.Close()
	if http.StatusNoContent != resp.StatusCode {
		fmt.Printf("Got error: %d\n", resp.StatusCode)
		json.NewDecoder(resp.Body).Decode(&gnunetError)
		fmt.Println(gnunetError.Code)
		fmt.Println(err)
		http.Redirect(w, r, "/name?label="+vars["label"] + "&error=" + gnunetError.Description, http.StatusSeeOther)
		return
	}
	http.Redirect(w, r, "/name/"+ vars["label"] + "?registered=true", http.StatusSeeOther)	
	return
}

func (t *Registrar) searchPage(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	http.Redirect(w, r, "/name/"+r.URL.Query().Get("label"), http.StatusSeeOther)	
	return
}

func (t *Registrar) expireRegistration(label string) (error) {
	var gnunetError GnunetError
	client := &http.Client{}
	req, _ := http.NewRequest(http.MethodDelete,t.GnunetUrl+"/namestore/" + t.RootZoneName + "/" + label, nil)
	resp, err := client.Do(req)
	resp.Body.Close()
	if err != nil {
		return err
	}
	if http.StatusNotFound == resp.StatusCode {
		return nil
	}
	if http.StatusNoContent != resp.StatusCode {
		fmt.Printf("Got error: %d\n", resp.StatusCode)
		err = json.NewDecoder(resp.Body).Decode(&gnunetError)
		return errors.New("GNUnet REST API error: " + gnunetError.Description)
	}
	return nil
}

func (t *Registrar) createOrUpdateRegistration(nsRecord *NamestoreRecord) (error) {
	var gnunetError GnunetError
	reqString, _ := json.Marshal(nsRecord)
	fmt.Println(nsRecord)
	client := &http.Client{}
	req, _ := http.NewRequest(http.MethodPut,t.GnunetUrl+"/namestore/" + t.RootZoneName, bytes.NewBuffer(reqString))
	resp, err := client.Do(req)
	if nil != err {
		return err
	}
	resp.Body.Close()
	if http.StatusNoContent != resp.StatusCode {
		fmt.Printf("Got error: %d\n", resp.StatusCode)
		err = json.NewDecoder(resp.Body).Decode(&gnunetError)
		return errors.New("GNUnet REST API error: " + gnunetError.Description)
	}
	return nil
}

func (t *Registrar) setupRegistrationMetadataBeforePayment(label string, zkey string, orderId string, paymentUntil time.Time) (error) {
	var namestoreRequest NamestoreRecord
	var delegationRecord RecordData
	var metadataRecord RecordData
	var registrationMetadata RegistrationMetadata
	delegationRecord.IsPrivate = true // Private until payment is through
	delegationRecord.IsRelativeExpiration = true
	delegationRecord.IsSupplemental = false
	delegationRecord.IsMaintenance = false
	delegationRecord.IsShadow = false
	delegationRecord.RecordType = guessDelegationRecordType(zkey)
	delegationRecord.RelativeExpiration = uint64(t.RelativeDelegationExpiration.Microseconds())
	delegationRecord.Value = zkey
	metadataRecord.IsPrivate = true
	metadataRecord.IsRelativeExpiration = true
	metadataRecord.IsSupplemental = false
	metadataRecord.IsMaintenance = true
	metadataRecord.IsShadow = false
	metadataRecord.RecordType = "TXT" // FIXME use new recory type
	metadataRecord.RelativeExpiration = uint64(t.RelativeDelegationExpiration.Microseconds())
	registrationMetadata = RegistrationMetadata{
		Paid: false,
		OrderID: orderId,
		NeedsPaymentUntil: paymentUntil,
		Expiration: uint64(time.Now().Add(t.RelativeRegistrationExpiration).UnixMicro()),
	}
	metadataRecordValue, err := json.Marshal(registrationMetadata)
	if nil != err {	
		return err
	}
	metadataRecord.Value = string(metadataRecordValue)
	namestoreRequest.RecordName = label
	namestoreRequest.Records = []RecordData{delegationRecord,metadataRecord}
	return t.createOrUpdateRegistration(&namestoreRequest)
}


func (t *Registrar) buyPage(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	var namestoreResponse NamestoreRecord
	var regMetadata *RegistrationMetadata
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	resp, err := http.Get(t.GnunetUrl + "/namestore/" + t.RootZoneName + "/" + vars["label"] + "?include_maintenance=yes")
	if err != nil {
		fmt.Printf("Failed to get zone contents")
		return
	}
	defer resp.Body.Close()
	if http.StatusOK == resp.StatusCode {
		respData, err := io.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Failed to get zone contents" + err.Error())
			return
		}
		err = json.NewDecoder(bytes.NewReader(respData)).Decode(&namestoreResponse)
		if err != nil {
			fmt.Printf("Failed to get zone contents" + err.Error())
			return
		}
		regMetadata, err = t.getCurrentRegistrationMetadata(vars["label"], &namestoreResponse)
		if err != nil {
			fmt.Printf("Failed to get registration metadata" + err.Error())
			return
		}
	} else if http.StatusNotFound != resp.StatusCode {
		http.Redirect(w, r, "/name/" + vars["label"] + "?error=Registration failed: Error determining zone status", http.StatusSeeOther)
		return	
	}
	var errorMsg = ""
	if nil != regMetadata {
		http.Redirect(w, r, "/name/"+vars["label"] + "?error=Registration failed: Pending buy order", http.StatusSeeOther)
		return
	}
	orderID, newOrderErr := t.Merchant.AddNewOrder(*t.RegistrationCost, "GNS registrar name registration", t.BaseUrl + "/name/" + vars["label"])
	if newOrderErr != nil {
		fmt.Println(newOrderErr)
		http.Redirect(w, r, "/name/"+vars["label"] + "?error=Registration failed: Unable to create order", http.StatusSeeOther)
		return
	}
	payto, paytoErr := t.Merchant.IsOrderPaid(orderID)
	if paytoErr != nil {
		http.Redirect(w, r, "/name/"+vars["label"] + "?error=Registration failed: Error getting payment data", http.StatusSeeOther)
		return	
	}
	qrPng, qrErr := qrcode.Encode(payto, qrcode.Medium, 256)
	if qrErr != nil {
		http.Redirect(w, r, "/name/"+vars["label"] + "?error=Registration failed: Error generating QR code", http.StatusSeeOther)
		return
	}
	paymentUntil := time.Now().Add(t.PaymentExpiration)
	err = t.setupRegistrationMetadataBeforePayment(vars["label"], r.URL.Query().Get("zkey"), orderID, paymentUntil)
	if err != nil {
		fmt.Println(err)
		http.Redirect(w, r, "/name/"+vars["label"] + "?error=Registration failed: Internal error", http.StatusSeeOther)
		return
	}
	encodedPng := base64.StdEncoding.EncodeToString(qrPng)
	fullData := map[string]interface{}{
		"qrCode": template.URL("data:image/png;base64," + encodedPng),
		"payto": template.URL(payto),
		"fulfillmentUrl": template.URL(t.BaseUrl + "/name/" + vars["label"]),
		"label":    vars["label"],
		"error":     errorMsg,
		"cost":     t.localizedAmountString(),
		"suffixHint":     t.SuffixHint,
	}
	t.BuyTpl.Execute(w, fullData)
	return
}

func (t *Registrar) getCurrentRegistrationMetadata(label string, nsRecord *NamestoreRecord) (*RegistrationMetadata, error) {
	var regMetadata RegistrationMetadata
	var haveMetadata = false
	for _, record := range nsRecord.Records {
		if record.RecordType == "TXT" {
			err := json.Unmarshal([]byte(record.Value), &regMetadata)
			if err != nil {
				fmt.Printf("Failed to get zone contents" + err.Error())
				return nil, err
			}
			haveMetadata = true
		}
	}
	if !haveMetadata {
		return nil, nil
	}
	if !regMetadata.Paid {
		payto, paytoErr := t.Merchant.IsOrderPaid(regMetadata.OrderID)
		if nil != paytoErr {
			return nil, errors.New("Error determining payment status")
		}
		if "" == payto {
			// Order was paid!
			regMetadata.Paid = true
			var newZkeyRecord RecordData
			var newMetaRecord RecordData
			for _, record := range nsRecord.Records {
				if isDelegationRecordType(record.RecordType) {
					record.IsPrivate = false
					newZkeyRecord = record
				}
				if record.RecordType == "TXT" {
					metadataRecordValue, err := json.Marshal(regMetadata)
					if nil != err {	
						return nil, err
					}
					record.Value = string(metadataRecordValue)
					newMetaRecord = record
				}
			}
			nsRecord.Records = []RecordData{newMetaRecord, newZkeyRecord}
			t.createOrUpdateRegistration(nsRecord)
		} else {
			if time.Now().After(regMetadata.NeedsPaymentUntil) {
				fmt.Printf("Payment request for %s has expired, removing\n", label)
				t.expireRegistration(label)
				return nil, nil
			}
		}
	} else {
		if time.Now().After(time.UnixMicro(int64(regMetadata.Expiration))) {
			fmt.Printf("Registration for %s has expired, removing\n", label)
			t.expireRegistration(label)
			return nil, nil
		}
	}
	return &regMetadata, nil
}

func guessDelegationRecordType(val string) (string) {
	if strings.HasPrefix(val, "000G00") {
		return "PKEY"
	} else {
		return "EDKEY"
	}
}

func isDelegationRecordType(typ string) (bool) {
	return typ == "PKEY" || typ == "EDKEY"
}

func (t *Registrar) namePage(w http.ResponseWriter, r *http.Request) {
	var namestoreResponse NamestoreRecord
	vars := mux.Vars(r)
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	var value = ""
	var registeredUntil = ""
	var regMetadata *RegistrationMetadata
	var registered = r.URL.Query().Get("registered") == "true"
	// FIXME redirect back if label empty
	resp, err := http.Get(t.GnunetUrl + "/namestore/" + t.RootZoneName + "/" + vars["label"] + "?include_maintenance=yes")
	if err != nil {
		http.Redirect(w, r, "/" + "?error=Failed to get zone contents.", http.StatusSeeOther)
		fmt.Printf("Failed to get zone contents")
		return
	}
	defer resp.Body.Close()
	if http.StatusOK == resp.StatusCode {
		respData, err := io.ReadAll(resp.Body)
		if err != nil {
			fmt.Println("Failed to get zone contents: " + err.Error())
			http.Redirect(w, r, "/" + "?error=Failed to get zone contents.", http.StatusSeeOther)
			return
		}
		err = json.NewDecoder(bytes.NewReader(respData)).Decode(&namestoreResponse)
		if err != nil {
			fmt.Println("Failed to get zone contents: " + err.Error())
			http.Redirect(w, r, "/" + "?error=Failed to get zone contents.", http.StatusSeeOther)
			return
		}
		regMetadata, err = t.getCurrentRegistrationMetadata(vars["label"], &namestoreResponse)
		if err != nil {
			fmt.Println("Failed to get registration metadata: " + err.Error())
			http.Redirect(w, r, "/" + "?error=Failed to get registration metadata.", http.StatusSeeOther)
			return
		}
	} else if http.StatusNotFound != resp.StatusCode {
		http.Redirect(w, r, "/" + "?error=Error retrieving zone information.", http.StatusSeeOther)
		return	
	}
	for _, record := range namestoreResponse.Records {
		if isDelegationRecordType(record.RecordType) {
			value = record.Value
		}
	}
	if regMetadata != nil {
		if regMetadata.Paid {
			registeredUntil = time.UnixMicro(int64(regMetadata.Expiration)).String() 
		}
	}
	fullData := map[string]interface{}{
		"label":    vars["label"],
		"error":     r.URL.Query().Get("error"),
		"cost":     t.localizedAmountString(),
		"available":    regMetadata == nil,
		"currentValue": value,
		"suffixHint":     t.SuffixHint,
		"registeredUntil":     registeredUntil,
		"registrationSuccess":     registered,
	}
	t.NameTpl.Execute(w, fullData)
	return
}

func (t *Registrar) setupHandlers() {
	t.Router = mux.NewRouter().StrictSlash(true)

	t.Router.HandleFunc("/", t.landingPage).Methods("GET")
	t.Router.HandleFunc("/name/{label}", t.namePage).Methods("GET")
	t.Router.HandleFunc("/name/{label}/buy", t.buyPage).Methods("GET")
	t.Router.HandleFunc("/name/{label}/register", t.registerName).Methods("GET")
	t.Router.HandleFunc("/search", t.searchPage).Methods("GET")

	/* ToS API */
	// t.Router.HandleFunc("/terms", t.termsResponse).Methods("GET")
	// t.Router.HandleFunc("/privacy", t.privacyResponse).Methods("GET")

	/* Config API */
	t.Router.HandleFunc("/config", t.configResponse).Methods("GET")

	/* Assets HTML */
	t.Router.PathPrefix("/css").Handler(http.StripPrefix("/css", http.FileServer(http.Dir("./static/css"))))
}

// Initialize the gnsregistrar instance with cfgfile
func (t *Registrar) Initialize(cfgfile string) {
	var identityResponse IdentityInfo
	_cfg, err := ini.Load(cfgfile)
	if err != nil {
		fmt.Printf("Failed to read config: %v", err)
		os.Exit(1)
	}
	t.Cfg = _cfg
	if t.Cfg.Section("gns-registrar").Key("production").MustBool(false) {
		fmt.Println("Production mode enabled")
	}
	landingTplFile := t.Cfg.Section("gns-registrar").Key("registrar_landing").MustString("web/templates/landing.html")
	t.LandingTpl, err = template.ParseFiles(landingTplFile)
	if err != nil {
		fmt.Println(err)
	}
	nameTplFile := t.Cfg.Section("gns-registrar").Key("registrar_name").MustString("web/templates/name.html")
	t.NameTpl, err = template.ParseFiles(nameTplFile)
	if err != nil {
		fmt.Println(err)
	}
	buyTplFile := t.Cfg.Section("gns-registrar").Key("buy_template").MustString("web/templates/buy.html")
	t.BuyTpl, err = template.ParseFiles(buyTplFile)
	if err != nil {
		fmt.Println(err)
	}
	paymentExp := t.Cfg.Section("gns-registrar").Key("payment_required_expiration").MustString("48h")
	recordExp := t.Cfg.Section("gns-registrar").Key("relative_delegation_expiration").MustString("24h")
	registrationExp := t.Cfg.Section("gns-registrar").Key("registration_expiration").MustString("8760h")
	t.RelativeRegistrationExpiration, _ = time.ParseDuration(registrationExp)
	t.RelativeDelegationExpiration, _ = time.ParseDuration(recordExp)
	t.PaymentExpiration, _ = time.ParseDuration(paymentExp)
	fmt.Println(t.RelativeDelegationExpiration)
	fmt.Println(t.RelativeRegistrationExpiration)
	costStr := t.Cfg.Section("gns-registrar").Key("registration_cost").MustString("KUDOS:0.3")
	t.RegistrationCost, err = talerutil.ParseAmount(costStr)
	t.BaseUrl = t.Cfg.Section("gns-registrar").Key("base_url").MustString("http://localhost:11000")
	t.SuffixHint = t.Cfg.Section("gns-registrar").Key("suffix_hint").MustString("example.alt")
	t.RootZoneName = t.Cfg.Section("gns-registrar").Key("root_zone_name").MustString("test")
	t.GnunetUrl = t.Cfg.Section("gns-registrar").Key("base_url_gnunet").MustString("http://localhost:7776")
	resp, err := http.Get(t.GnunetUrl + "/identity/name/" + t.RootZoneName)
	if err != nil {
		fmt.Printf("Failed to get zone key")
		return
	}
	defer resp.Body.Close()
	if http.StatusNotFound == resp.StatusCode {
		fmt.Printf("Zone not found.")
		os.Exit(1)
	} else if http.StatusOK == resp.StatusCode {
		respData, err := io.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Failed to get zone contents" + err.Error())
			os.Exit(1)
		}
		err = json.NewDecoder(bytes.NewReader(respData)).Decode(&identityResponse)
		if err != nil {
			fmt.Printf("Failed to get zone contents" + err.Error())
			os.Exit(1)
		}
		t.RootZoneKey = identityResponse.Pubkey
	} else {
		fmt.Printf("Failed to get zone contents" + err.Error())
		os.Exit(1)
	}
	merchURL := t.Cfg.Section("gns-registrar").Key("base_url_merchant").MustString("https://backend.demo.taler.net")
	merchToken := t.Cfg.Section("gns-registrar").Key("merchant_token").MustString("sandbox")
	t.Merchant = merchant.NewMerchant(merchURL, merchToken)
	t.setupHandlers()
}