summaryrefslogtreecommitdiff
path: root/c2ec/main.go
blob: f8e902985e7ccf3c4f71f863de01e1befd0ac5c9 (plain)
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
package main

import (
	"context"
	"errors"
	"fmt"
	"net"
	http "net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

const GET = "GET "
const POST = "POST "

const BANK_INTEGRATION_API = "/c2ec"
const WIRE_GATEWAY_API = "/wire"

const DEFAULT_C2EC_CONFIG_PATH = "c2ec-config.yaml"

var CONFIG C2ECConfig

var DB C2ECDatabase

// This map contains all clients initialized during the
// startup of the application. The clients SHALL register
// themselfs during the setup!!
var PROVIDER_CLIENTS = map[string]ProviderClient{}

// Starts the c2ec process.
// The program takes following arguments (ordered):
//  1. path to configuration file (.yaml | .ini style format) (optional)
//
// The startup follows these steps:
//  1. load configuration or panic
//  2. setup database or panic
//  3. setup provider clients
//  4. setup attestor
//  5. setup routes for the bank-integration-api
//  6. setup routes for the wire-gateway-api
//  7. listen for incoming requests (as specified in config)
func main() {

	LogInfo("main", fmt.Sprintf("starting c2ec at %s", time.Now().Format(time.UnixDate)))

	cfgPath := DEFAULT_C2EC_CONFIG_PATH
	if len(os.Args) > 1 && os.Args[1] != "" {
		cfgPath = os.Args[1]
	}
	cfg, err := Parse(cfgPath)
	if err != nil {
		panic("unable to load config: " + err.Error())
	}
	if cfg == nil {
		panic("config is nil")
	}
	CONFIG = *cfg

	DB, err = setupDatabase(&CONFIG.Database)
	if err != nil {
		panic("unable to connect to datatbase: " + err.Error())
	}

	err = setupProviderClients(&CONFIG)
	if err != nil {
		panic("unable initialize attestors: " + err.Error())
	}
	LogInfo("main", "provider clients are setup")

	attestorCtx, attestorCancel := context.WithCancel(context.Background())
	defer attestorCancel() // run cancel anyway when main exits.
	attestorErrs := make(chan error)
	RunAttestor(attestorCtx, attestorErrs)
	LogInfo("main", "attestor is running")

	// TODO run retry process here

	router := http.NewServeMux()

	setupBankIntegrationRoutes(router)

	setupWireGatewayRoutes(router)

	server := http.Server{
		Handler: router,
	}

	if CONFIG.Server.UseUnixDomainSocket {

		socket, err := net.Listen("unix", CONFIG.Server.UnixSocketPath)
		if err != nil {
			panic("failed listening on socket: " + err.Error())
		}

		// cleans up socket when process fails and is shutdown.
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt, syscall.SIGTERM)
		go func() {
			<-c
			os.Remove(CONFIG.Server.UnixSocketPath)
			os.Exit(1)
		}()

		// move this to goroutine
		LogInfo("main", "serving at unix-domain-socket "+server.Addr)
		if err = server.Serve(socket); err != nil {
			panic(err.Error())
		}
	} else {

		// move this to goroutine
		server.Addr = fmt.Sprintf("%s:%d", CONFIG.Server.Host, CONFIG.Server.Port)
		LogInfo("main", "serving at "+server.Addr)
		if err = server.ListenAndServe(); err != nil {
			panic(err.Error())
		}
	}

	// TODO : do proper

	// since listening for incoming request, attesting payments and
	// retrying payments are three separated processes who can fail
	// we must take care of this here. The main process is used to
	// dispatch incoming http request and parent of the attestation
	// and retry processes. If the main process fails somehow, also
	// attestation and retries will end. But if somehow the attestation
	// or retry process fail, they will be restarted and the error is
	// written to the log. If some setup tasks are failing, the program
	// panics.
	// for {
	// 	select {
	// 	case attestationError := <-attestorErrs:
	// 		LogError("main", attestationError)
	// 	case <-attestorCtx.Done():
	// 		// The attestation process died for some reason. let's restart it.
	// 		attestorCtx, attestorCancel = context.WithCancel(context.Background())
	// 		defer attestorCancel() // does this the right thing?
	// 		RunAttestor(attestorCtx, attestorErrs)
	// 	}
	// }
}

func setupDatabase(cfg *C2ECDatabseConfig) (C2ECDatabase, error) {

	return NewC2ECPostgres(cfg)
}

func setupProviderClients(cfg *C2ECConfig) error {

	if DB == nil {
		return errors.New("setup database first")
	}

	for _, provider := range cfg.Providers {

		p, err := DB.GetTerminalProviderByName(provider.Name)
		if err != nil {
			return err
		}

		if p == nil {
			if cfg.Server.IsProd || cfg.Server.StrictAttestors {
				panic("no provider entry for " + provider.Name)
			} else {
				LogWarn("non-strict attestor initialization. skipping", provider.Name)
				continue
			}
		}

		if !cfg.Server.IsProd {
			// Prevent simulation client to be loaded in productive environments.
			if p.Name == "Simulation" {

				simulationClient := new(SimulationClient)
				err := simulationClient.SetupClient(p)
				if err != nil {
					return err
				}
			}
		}

		if p.Name == "Wallee" {

			walleeClient := new(WalleeClient)
			err := walleeClient.SetupClient(p)
			if err != nil {
				return err
			}
		}

		// For new added provider, add the respective if-clause
	}

	return nil
}

func setupBankIntegrationRoutes(router *http.ServeMux) {

	router.HandleFunc(
		GET+BANK_INTEGRATION_API+BANK_INTEGRATION_CONFIG_PATTERN,
		bankIntegrationConfig,
	)

	router.HandleFunc(
		POST+BANK_INTEGRATION_API+WITHDRAWAL_OPERATION_BY_WOPID_PATTERN,
		handleWithdrawalRegistration,
	)

	router.HandleFunc(
		GET+BANK_INTEGRATION_API+WITHDRAWAL_OPERATION_BY_WOPID_PATTERN,
		handleWithdrawalStatus,
	)

	router.HandleFunc(
		POST+BANK_INTEGRATION_API+WITHDRAWAL_OPERATION_PAYMENT_PATTERN,
		handlePaymentNotification,
	)

	router.HandleFunc(
		POST+BANK_INTEGRATION_API+WITHDRAWAL_OPERATION_ABORTION_PATTERN,
		handleWithdrawalAbort,
	)
}

func setupWireGatewayRoutes(router *http.ServeMux) {

	router.HandleFunc(
		GET+WIRE_GATEWAY_API+WIRE_GATEWAY_CONFIG_PATTERN,
		wireGatewayConfig,
	)

	router.HandleFunc(
		POST+WIRE_GATEWAY_API+WIRE_TRANSFER_PATTERN,
		transfer,
	)

	router.HandleFunc(
		GET+WIRE_GATEWAY_API+WIRE_HISTORY_INCOMING_PATTERN,
		historyIncoming,
	)

	router.HandleFunc(
		GET+WIRE_GATEWAY_API+WIRE_HISTORY_OUTGOING_PATTERN,
		historyOutgoing,
	)

	router.HandleFunc(
		POST+WIRE_GATEWAY_API+WIRE_ADMIN_ADD_INCOMING_PATTERN,
		adminAddIncoming,
	)
}